This question already has an answer here:
这个问题在这里已有答案:
- Conditional Variable vs Semaphore 5 answers
- 条件变量与信号量5答案
Why should we use wait() and signal() operation in multithreading applications?
为什么我们应该在多线程应用程序中使用wait()和signal()操作?
I'm relatively new to multithreading and somewhat understand mutual exclusion but I need a better understanding of how wait() and signal() come into the equation.
我对多线程相对较新,并且有点理解互斥,但我需要更好地理解wait()和signal()如何进入等式。
It seems I'm achieving thread safety by only using lock() and unlock(). Am I wrong?
看来我只使用lock()和unlock()来实现线程安全。我错了吗?
Can someone give me an example of wait/signal being used and wait and signal not being used with lock/unlock? What are the benefits to using wait/signal over just lock/unlock?
有人能给我一个等待/信号使用的例子,等待和信号没有用于锁定/解锁?使用等待/信号而不是锁定/解锁有什么好处?
Thanks.
谢谢。
2 个解决方案
#1
1
I work with computational maths/science so my examples come from there.
我从事计算数学/科学工作,所以我的例子来自那里。
If you were doing a reduce operation such as a dot product (need to sum many calculations) then lock and unlock are useful as the order of the sum does not matter and if it's free the thread should go for it.
如果您正在进行缩减操作,例如点积(需要总结许多计算),那么锁定和解锁是有用的,因为总和的顺序无关紧要,如果它是空闲的,则线程应该为它。
If you were solving a PDE over time before you can take the next time step the previous time step needs to be completed, a lock/unlock wouldn't work as even if the data is free for modification the prerequisite calculations may not have been done, this is where you would use a wait/signal.
如果您在下一个时间步骤之前解决PDE需要完成上一个时间步骤,则锁定/解锁将不起作用,即使数据可以*修改,也可能没有完成先决条件计算,这是你使用等待/信号的地方。
#2
0
Cramer your answer gave me good hints but the answer on this page was exactly the explanation I needed.
Cramer你的回答给了我很好的提示,但这页上的答案正是我需要的解释。
Conditional Variable vs Semaphore
条件变量与信号量
#1
1
I work with computational maths/science so my examples come from there.
我从事计算数学/科学工作,所以我的例子来自那里。
If you were doing a reduce operation such as a dot product (need to sum many calculations) then lock and unlock are useful as the order of the sum does not matter and if it's free the thread should go for it.
如果您正在进行缩减操作,例如点积(需要总结许多计算),那么锁定和解锁是有用的,因为总和的顺序无关紧要,如果它是空闲的,则线程应该为它。
If you were solving a PDE over time before you can take the next time step the previous time step needs to be completed, a lock/unlock wouldn't work as even if the data is free for modification the prerequisite calculations may not have been done, this is where you would use a wait/signal.
如果您在下一个时间步骤之前解决PDE需要完成上一个时间步骤,则锁定/解锁将不起作用,即使数据可以*修改,也可能没有完成先决条件计算,这是你使用等待/信号的地方。
#2
0
Cramer your answer gave me good hints but the answer on this page was exactly the explanation I needed.
Cramer你的回答给了我很好的提示,但这页上的答案正是我需要的解释。
Conditional Variable vs Semaphore
条件变量与信号量