I have two threads in my application. thread 2 must wait for thread1 but it doesn't because thread2 runs before and takes the control, so how can I give the control to the other the first time?
In the main functionI create the mutex: CreateMutex(NULL,FALSE,NULL) I think with the second parameter to FALSE the main thread doesn't take the mutex the first time. After that I create the second thread and in its function wait for this mutex but this thread is the first so it takes the mutex.
in the main function I call and another function at the same time and wait for the mutex too, but I need that this function takes the mutex first...
The thing is that with semaphore I can control what thread begins first but with mutex I don't know how I can do it.
The first thread is the main function, so it starts first. Than it creates another thread. Afterwards the first thread must sleep 2 seconds because the thread 2 must open a connection and then both have a wait for the mutex. I wanted that thread 1 takes the mutex before. I wanted to know how can I do it.
main()
{
createmutex()
lockmutex()
createthread2()
//do the work here
release_mutex()
}
thread_function()
{
while(mutex_lock()) //untill thread1 doesnt finish, this will block the thread
{
sleep(2);
}
lock_mutex()
//do the work
release_mutex()
}
The problem is that thread2 must open a connection before main thread does its works... I'm trying this:
I create a semaphore to synchronize this first step, that is, the second thread open the connection and when it's ready releases the semaphore. Then the main thread begins and it has another semaphore that blocks the second thread, it works... (actually I'm using semaphore with maximum count to 1 that it's the same like a mutex...)
main create the thread2
thread2 open a connection and stop there
main use the connection and complete the work
thread2 then proceed when main finishes.
correct?? so your problem is solved with the semaphore??