开发者

empty while synchronization in c++?

static char szInfo[256];
static volatile bool bIsLocked = false;

static void ApiFunc() {
    while (bIsLocked) { }
    bIsLocked = true;
    //do something to szInfo
    bIsLocked = false;
}

It has been awhile since I have done any threading in C++, Is this safe enough? This is a much simpler solution to me than using a mutex, but 开发者_如何学运维why would I use windows mutex instead?


You would use a mutex (or more likely a critical section) because that would work. This code does not synchronise. Multiple threads can enter the critical region.

And of course, real locks don't spin. Well, spin-locks do, but you need a deep understanding of the performance implications of a spin-lock before electing to use one.


It is not thread safe at all!

Thread #1 gets trough check, but do not set boolean. Thread #2 comes in this time in the critical session.


What you've implemented is almost Peterson's Algorithm. As the above posters have said this is not thread safe, as there is no mechanism to prevent both threads entering the critical section at the same time. You can try implementing Peterson's Algorithm properly, but it would be far more effective to use a true mutex.

The major problem with your approach is that a thread can be interrupted after exiting the while loop, but before they set the bool to true. If this happens then your two threads enter the critical section together. If you have more than two threads then you will have multiple threads that exit the loop at the same time.


It's not safe at all. volatile has no defined semantics with regards to threads. At most, it will prevent the compiler from suppressing the assignments completely (since their net effect is a no-op), but it will not prevent the compiler from reordering accesses to szInfo around accesses to bIsLocked, and it will not prevent the hardware from any reordering what so ever, or even suppressing the bIsLocked = true completely.


This code won't work the way you hope it does. There's a race condition between the end of the while loop and when you set locked to true. It also CPU busy-waits for the lock while synchronization primatives are able to yield CPU while waiting.

A better way to solve the problem is just to use local data rather than a global buffer. Then you might not even need to lock at all! If you do in fact need to synchronize threads, use a mutex or critical section because those will actually work.


Use Locks.

A talk on the perils of threading without locks, from BoostCon 2010: http://blip.tv/file/4211197/

slides, notes, at: http://boostcon.boost.org/2010-resources

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜