More thread ID problems
Posted on 2006-04-05
I have a multithreaded app. In this app are several functions, only one of which can ever be called at one time. I control access to these functions via a variable in a containing class called "m_bBusy". Access to this variable is protected by a CCriticalSection.
Now, when one of these functions is running, m_bBusy gets set to TRUE. If any other thread tries to access one of these functions and m_bBusy is TRUE, it fails. No blocking, just a simple fail with a return code something along the lines of a custom enum type TIMEOUT. When a function ends, m_bBusy gets set to FALSE.
So all that is fairly cool.
However. I am at the stage now where one of these functions may call into another of these functions. The second call will always fail however as the first function call has set m_bBusy to TRUE. So I am failing when what I have done in theory is fine.
Now, I have asked a previous question on how to get the ID of a thread, the idea being that when testing m_bBusy, I should see if the ID of the thread that set the busy state is the same as the one that is trying to set it again. If it is, then it is safe to carry on.
//Test m_bBusy, it is FALSE so Set m_bBusy to TRUE
//.. do some work
// Call second function
//.. do some more work
// Set m_bBusy to FALSE
// Test m_bBusy: it is TRUE, but instead of quitting, test the ID of the thread that set the state. If it is the same as this thread's ID, carry on. Otherwise, return a timeout.
See what I am trying to do ? Now, AlexFM kindly advised me in my last question that I can get the ID of a thread when I create one via AfxBeginThread through CWinThread::m_nThreadID. I need this value to be available in all function calls I make in this thread: but how ?
I could pass it as a member of a data structure I pass to my thread function, but then every other function I call within my thread function has to have provision for this too. And this is impractical. Besides, what if someone calls one of these functions in the *main* thread, whilst a worker thread created with AfxBeginThread is doing something ? How do I get the ID of the main thread in this case ?