Symbian
Symbian OS Library

FAQ-0504 Why does my code sometimes gets stuck waiting for a thread to die?

[Index][spacer] [Previous] [Next]



 

Classification: C++ Category: Threads & Processes
Created: 07/24/2000 Modified: 09/04/2001
Number: FAQ-0504
Platform: ER5, Symbian OS v6.0, Symbian OS v6.1

Question:
I have the following bit of code:
TRequestStatus stat;
iSem.Signal();
iOther.Logon(stat);
User::WaitForRequest(stat);

where the class members are defined as:
RThread iOther;
RSemaphore iSem;

The semaphore is used to tell the other thread that it is no longer needed and that it can go ahead and die. The point of the User::WaitForRequest() call is to actually wait until the other thread dies before continuing. Sometimes, however, this call does not return, other times it does. The only difference between the two different outcomes is the exact timing of the execution.


Answer:
The reason for this is that you can only Logon to a thread that is alive. It is possible that the other thread gets in and runs after the iSem.Signal() call and dies before the call to Logon on is made, in this case the User::WaitForRequest(stat) will not return. However, if the other thread has not died before the call to Logon then things will work fine. Thus, to fix the problem, you need to move the Logon to before the Signal.
So the code should be:

TRequestStatus stat;
iOther.Logon(stat);
iSem.Signal();
User::WaitForRequest(stat);