Subj : Re: Question : usage of conditional variables. To : comp.programming.threads From : Uenal Mutlu Date : Thu Jun 09 2005 12:16 pm "Jamie" wrote > > I am quite new to multi-threaded programming, and I am now trying to > make two threads and communicate with each other by using conditional > variables. However, I got stuck in a problem. If anyone give me any > idea, I would really appreciate it!! > > Program Summary: > 1) Making two threads (tA, tB) > 2) tA send a conditional signal to tB > 3) tB recv a conditional signal > 4) tB send a conditional signal to tA > 5) tA recv a conditional signal > 6) repeat through 2 to 5. > > Issue: > I tried to run this program with a set of mutex & conditional variable > and also two sets of mutex & conditional variables(one for tA->tB, the > other for tB->tA). But same issue happened. > I ran it on VMWare and it's quite slow. When I run around 300 loop, it > looks working well, it works as the order I expected. However, when I > increase the number of loop more than that, the order get tangled and > it looks waiting a signal forever and don't get a signal at all.. > > Should it be guaranted that pthread_cond_wait() is called before > pthread_cond_signal() is called? Try the following pseudo C++ code as a model framework: template class CondVar { public: CondVar(); ~CondVar(); void Set(T val); T Get(); void WaitFor(T val); //... }; CondVar cvEnding; // gets set externally CondVar cv; // used for signalling void procA() { while (!cvEnding.Get()) { //... cv.WaitFor(false); //...do something cv.Set(true); } cv.Set(true); } void procB() { while (!cvEnding.Get()) { //... cv.WaitFor(true); //...do something cv.Set(false); } cv.Set(false); } void start() { cv.Set(false); CreateThread(procA); CreateThread(procB); cvEnding.WaitFor(true); //... } .