Re: problems with Threads.
You are doing it the wrong way - you should acquire the semaphore at the beginning of your operation and release it afterwards. Unfortunately this will not cause both threads to do their work in sequence of A-B-A-B-etc. For that you need two semaphores or wait conditions. Each thread has to wait on one condition (and the other on the other) and when you want the other thread to run, signal the appropriate condition.
Re: problems with Threads.
i try with two semaphores but my output A-B-A-B.. is not coming.The code is below and where i release the semaphores for getting the proper result.
Code:
void MyThread::run()
{
for(int lCount = 0; lCount < 5; lCount++)
{
if(messageStr == "A")
{
cout << "lCount in ThreadA:" << lCount << endl;
iSemA->acquire(1);
cout << "Thread : " << messageStr.toAscii().data() << endl;
iSemB->release(1);
}
else
{
cout << "lCount in ThreadB:" << lCount << endl;
iSemB->acquire(1);
cout << "Thread : " << messageStr.toAscii().data() << endl;
iSemA->release(1);
}
}
}
Re: problems with Threads.
You have to set one semaphore to 0 and the other one to 1 initially so that only one thread can run at the beginning. Otherwise you'll never be acquiring a semaphore when it's at 0. I would use wait conditions here though. Or a single thread...