开发者

A basic question on multihreading

For example I have a resource lock. So a multithreaded function checks if it's set before accessing a resource, then if it's not s开发者_Go百科ets it

Is there a tiny possibility that between checking and setting, another thread would have set the same lock?


Yes, there is such possibility. You may checkout double-checked locking.


Depends how you want it to work. Read the man page for mutex_lock. The checking whether a lock is set is superfluous in this case, since the very act of setting the mutex pauses the thread until the mutex is available (and so any sort of if(resource_unavailable) { wait for availability } code becomes unnecessary).


You don't check the state of a lock first to then acquire it. What you do is to just acquire it, specifying that you do not want to block or wait for it. The call will fail immediately if the lock is held by another thread. The "lock acquire" call is implemented as an atomic operation.

Many implementations provide a specific tryLock() function that achieves what I described above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜