I am new to threads and multithreading.(Win socket API) I am trying to achieve the sequence of tasks in 2 threads with proper synchronization.
no. of threads 2 : Thread_A and Thread_B
Thread_A{
print task_A
print task_D
}
Thread_B{
print task_B
print task_C
}
The expected output should be print task_A , print task_B, print task_C, print task_D.
do i need to use 2 semaphores or 1 can be use ??
Thread_A{
while(1){
wait semaphore
print task_A
release semaphore
wait semaphore
print task_D
release semaphore
}
}
Thread_B{
while(1){
wait semaphore
print task_B
print task_C
release semaphore
}
}
for once it goes A,B,C,D but second time B,C, A,B
I have tried with condition variables to ensure that task 1 is performed before task 2 and also for task 3 and 4. ref : Windows control variable Inital value of done and flag is 0
Thread 1
while(1){
EnterCriticalSection (&Tx_data);
while (done == 1 )
{
SleepConditionVariableCS (&Status, &Tx_data, INFINITE);
}
printf("\n 1 "); // task A
done =1;
flag =0;
LeaveCriticalSection (&Tx_data);
WakeConditionVariable (&Status);
EnterCriticalSection (&Tx_data);
while (flag == 0 )
{
SleepConditionVariableCS (&flags, &Tx_data, INFINITE);
}
printf(" 4 "); // task D
LeaveCriticalSection (&Tx_data);
WakeConditionVariable (&Status);
}
Thread 2
while(1){
EnterCriticalSection (&Tx_data);
while (done == 0 )
{
SleepConditionVariableCS (&Status, &Tx_data, INFINITE);
}
printf(" 2 ");// task B
printf(" 3 ");// task C
done =0;
flag =1;
LeaveCriticalSection (&Tx_data);
WakeConditionVariable (&flags);
WakeConditionVariable (&Status);
}
The result ok and look like
1 2 3 4
1 2 3 4
is this approach with the use of condition variable to sequentially operate 1 2 3 4 tasks correct ?. It works for few tests, but is it reliable and fail proof ?