Interview Question
- 0of 0 votes
Answerstatic HANDLE mutex[2];
- gs November 24, 2012 in United States
static unsigned __stdcall threadFunc1(void *v){
while(1)
{
WaitForSingleObject(mutex[0], INFINITE);
if (k>=10)
return 0;
cout<<"\n\tWELL ThreadID : 1 : ";
cout<<GetCurrentThreadId()<<" :: "<<k++<<endl;
cout<<flush;
ReleaseMutex(mutex[1]);
}
return 0;
};
static unsigned __stdcall threadFunc2(void *v){
while(1)
{
WaitForSingleObject(mutex[1], INFINITE);
if (k>=10)
return 0;
cout<<"\n\tWELL ThreadID : 2 : ";
cout<<GetCurrentThreadId()<<" :: "<<k++<<endl;
cout<<flush;
ReleaseMutex(mutex[0]);
}
return 0;
};
int main()
{
unsigned int t1;
HANDLE h[2];
int *ii=&i;
mutex[0] = CreateMutex(0, 0, 0);
mutex[1] = CreateMutex(0, 0, 0);
h[0] = (HANDLE)_beginthreadex(0,0,&threadFunc1,(void *)ii,0,&t1);
h[1] = (HANDLE)_beginthreadex(0,0,&threadFunc2,(void *)ii,0,&t1);
WaitForMultipleObjects(2, h, true, INFINITE);
CloseHandle(h[0]);
CloseHandle(h[1]);
CloseHandle(mutex[0]);
CloseHandle(mutex[1]);
cin>>i;
return 0;
}
Output :
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 01
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 23
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 45
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 67
WELL ThreadID : 1 :
WELL ThreadID : 2 : 47124264 :: :: 89
why is output not syncronized ?| Report Duplicate | Flag | PURGE
Your code doing this:
- m@}{ November 26, 2012thread1:
mutex0.lock();
working with cout
mutex1.unlock();
thread2:
mutex1.lock();
working with cout
mutex0.unlock();
"cout" is buffered output and not thread safe. So, it's not safe to write from different threads simultaneously to cout.