Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

wait and notify in C/C++ shared memory

How to wait and notify like in Java In C/C++ for shared memory between two or more thread?I use pthread library.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of the Java object that you would use to wait/notify, you need two objects: a mutex and a condition variable. These are initialized with pthread_mutex_init and pthread_cond_init.

Where you would have synchronized on the Java object, use pthread_mutex_lock and pthread_mutex_unlock (note that in C you have to pair these yourself manually). If you don't need to wait/notify, just lock/unlock, then you don't need the condition variable, just the mutex. Bear in mind that mutexes are not necessarily "recursive", This means that if you're already holding the lock, you can't take it again unless you set the init flag to say you want that behaviour.

Where you would have called java.lang.Object.wait, call pthread_cond_wait or pthread_cond_timedwait.

Where you would have called java.lang.Object.notify, call pthread_cond_signal.

Where you would have called java.lang.Object.notifyAll, call pthread_cond_broadcast.

As in Java, spurious wakeups are possible from the wait functions, so you need some condition which is set before the call to signal, and checked after the call to wait, and you need to call pthread_cond_wait in a loop. As in Java, the mutex is released while you're waiting.

Unlike Java, where you can't call notify unless you hold the monitor, you can actually call pthread_cond_signal without holding the mutex. It normally doesn't gain you anything, though, and is often a really bad idea (because normally you want to lock - set condition - signal - unlock). So it's best just to ignore it and treat it like Java.

There's not really much more to it, the basic pattern is the same as Java, and not by coincidence. Do read the documentation for all those functions, though, because there are various flags and funny behaviours that you want to know about and/or avoid.

In C++ you can do a bit better than just using the pthreads API. You should at least apply RAII to the mutex lock/unlock, but depending what C++ libraries you can use, you might be better off using a more C++-ish wrapper for the pthreads functions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...