LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   pthread signal problem (https://www.linuxquestions.org/questions/linux-software-2/pthread-signal-problem-113252/)

xinwang00 11-06-2003 09:14 PM

pthread signal problem
 
Hi,

I am working on a pthread project and this problem really confuses me. It seems that the broadcast doesn't wake up all waiting threads. Below is the pseudocode (it has been simplified a lot to show the problem):

Thread A:
.........
pthread_mutex_lock(myMutex);
.........
cout<<"thread A signals signal1"<<endl;
pthread_cond_signal(signal1);
cout<<"thread A waits for signal2"<<endl;
pthread_cond_wait(signal2);
.........
pthread_mutex_unlock(myMutex);
.........

Thread B:
.........
pthread_mutex_lock(myMutex);
.........
cout<<"thread B waits for signal1"<<endl;
pthread_cond_wait(signal1);
.........
(if I add "sleep(1)" here, then the bug is gone)
cout<<"thread B broadcasts signal2);
pthread_cond_broadcast(signal2);
.........
pthread_mutex_unlock(myMutex);
.........

The calling order is:
thread B waits for signal1
thread A signals signal1
thread A waits for signal2
thread B broadcasts signal2 // this broadcast doesn't wake up thread A!

If let B sleeps for 1 sec before broadcast (as commented above in the code), then the bug is gone. Also the bug seems only happen when I run it on a single processor machine.

Do you have any clue why this happens? Thank you ver much!

MartinN 11-07-2003 02:27 AM

There is a forum for programming questions where you could possibly get better answers. I have to admit I'm a little out of training on threads.

From your description of the problem, I'd say you have a race condition. There is no guarantee that your "Thread A" really does wait on signal 2. Even though you have a trace print-out just above the line
pthread_cond_wait(signal2);
there is nothing that says that this line is executed.
It could be that thread A's execution is interrupted between the print-out and the waiting. Then thread B sends the broadcast before thread A waits for it.

The more I think about it, the more likely this scenario seems to me. Do you agree?

Regards
Martin

xinwang00 11-07-2003 12:05 PM

Martin,

Thanks for your reply!

It seems to me that after thread B awakens by signal1 of thread A, since thread A holds myMutex, thread B must immediately block on the myMutex. Thread A continues until it waits for signal2 and release myMutex. THen thread B gets the chance to run. I think by the time thread B broadcasts, thead A should have already been waiting.

Also if it is the scenario as you said, the problem should not be solved by letting thread B sleep(1) before broadcast.

(Please note that I only have this problem when I run it on a single processor machine. No problem if run on 2-CPU machine.)

Thanks,

Xin


All times are GMT -5. The time now is 01:07 PM.