Click to See Complete Forum and Search --> : learning multithreading through example


Pandiani
June 21st, 2005, 05:59 AM
Hello, I found this simple multithreading application:

#include <stdio.h>
#include <windows.h>


void read();
void write();

int state, num;

enum {Read, Write};
HANDLE hMutex, hWriteDone, hReadDone;

int main(void)
{
HANDLE hThreads[2];
int id;

state = 1;
hThreads[0] = CreateThread(0,0,(LPTHREAD_START_ROUTINE)write,0,0,&id);
hThreads[1] = CreateThread(0,0,(LPTHREAD_START_ROUTINE)read,0,0,&id);
hMutex = CreateMutex(NULL, FALSE, NULL);
hWriteDone = CreateEvent(NULL,TRUE,FALSE,NULL);
hReadDone = CreateEvent(NULL,TRUE,FALSE,NULL);

WaitForMultipleObjects(2,hThreads,TRUE,INFINITE);

CloseHandle(hThreads[0]);
CloseHandle(hThreads[1]);

}

void write()
{
int i;

for(i = 0; i < 10; i++)
{
while (1)
{
WaitForSingleObject(hMutex,INFINITE);

if(state == Read)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hReadDone,INFINITE);
continue;
}
break;
}
num = i;
printf("Write Done %d!\n",i+1);
state = Read;
ReleaseMutex(hMutex);
PulseEvent(hWriteDone);
}
}
void read()
{
int i;

for (i = 0; i < 10; i++)
{
while(1)
{
WaitForSingleObject(hMutex,INFINITE);

if (state == Write)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hWriteDone,INFINITE);
continue;
}

break;
}
printf("Read Done %d\n",i+1);
state = Write;
ReleaseMutex(hMutex);
PulseEvent(hReadDone);
if (num == 9)
{
printf("End of data!\n");
ExitThread(0);
}
}

}



I'm complete beginer in multithreading, but I do understand some things.

What I don't understand is why ReleaseMutex is needed in if (state ==...) part of program?

I'm really having a tough time to understand all this. Can you recommend some good multithreading tutorial for a beginer?
I found Multithreading for rookies on MSDN, but it is not very helpful for me.

Thanks

Andreas Masur
June 21st, 2005, 06:53 AM
Take a look at the following:

FAQs:

How to create a worker thread? (http://www.codeguru.com/forum/showthread.php?t=312452)
How to end a thread? (http://www.codeguru.com/forum/showthread.php?t=305166)
How to use member functions as thread functions? (http://www.codeguru.com/forum/showthread.php?t=312453)
How to access UI elements from a thread in MFC? (http://www.codeguru.com/forum/showthread.php?t=312454)


MSDN:

Multiple Threads (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/multiple_threads.asp)
Synchronization (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization.asp)
Multithreading mit C++ und MFC (http://msdn.microsoft.com/library/deu/default.asp?url=/library/DEU/vccore/html/_core_multithreading_with_c.2b2b_.and_mfc.asp)