如果我有一个关键部分,我必须采用锁上的方法。
while(lock)
{
//do nothing
}
lock = true;
// code of critical section
lock = false;
然而,我怀疑,因为理论上,几条线索可以执行 while(lock)
(检查并看到它=假),并一起进入关键部分,因为 while(lock)
和 lock= true;
没有在一个连续的块中执行。 我错了吗? 还是这确实不是一个安全的方法?
如果我有一个关键部分,我必须采用锁上的方法。
while(lock)
{
//do nothing
}
lock = true;
// code of critical section
lock = false;
然而,我怀疑,因为理论上,几条线索可以执行 while(lock)
(检查并看到它=假),并一起进入关键部分,因为 while(lock)
和 lock= true;
没有在一个连续的块中执行。 我错了吗? 还是这确实不是一个安全的方法?
这是“几乎安全 ”, 即根本不安全。 它所缺少的正是你所看到的—— 多重线索可以看到< code> lock = freed = 错误 < /code> 并输入关键部分。 它需要原子操作, 必须得到硬件的支持 — 一种保证只有一条行刑才能获得锁的方法 。
也就是说,如果您撰写的系统 能够幸存 相互排斥的失败, 并且可以适应工作 通常情况下的失败(或许是伐木, 或者偶尔的混杂的输入 不一定会导致完全失败), 这种模式可以“sorta”工作...
你说的对,这不安全,没什么比这更糟糕的了。
编辑 : 不, 确实, 真的没有关于此构造的更多话要说 。 这不是一个旋转锁, 也不是一个旋转锁。 对于旋转锁, 您需要像这样模糊的东西 :
// note: incomplete, not reentrant, not intended for real use
atomic_type spin_lock = 0;
// enter the spin lock:
int prev_value;
while ((prev_value = test_and_set(&spin_lock, 1)) != 0 || spin_lock != 1)
;
// code of critical section
// release the spin lock:
test_and_set(&spin_lock, 0);
这里重要的一点是,要输入旋转锁, 您需要获取上一个值, 并设定新的值 解剖 em> 。 然后您必须验证“ em> your em> 写到锁上, 将它从“ 不拥有” 状态改为“ 拥有 ” 状态 。
您正在尝试执行的称为“ spinlock ” 。 新的 C 标准, C11, 执行一种原始数据类型, 叫做 < code> atomic_ flag code >, 可以这样使用。 几乎所有的现代硬件都支持它, 但不幸的是,大多数编译者还没有在语法上支持它, 但有自己的扩展。 E. gcc 已经为此建立了 < code\\\ sync_ lock_ test_ and_ set 和 < code\\sync_ lock_ release 。
For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...
最好、最小、最快、开放的来源、C/C++ 3d 提供方(在3ds max模型的支持下),而不是通用公平市价,
Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...
I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...
I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...
I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...
Is there anything other than DDD that will draw diagrams of my data structures like DDD does that runs on Linux? ddd is okay and runs, just kind of has an old klunky feeling to it, just wanted to ...
Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...