-
Multi-threading
I have created a Multi-threaded code, where each thread prints hello world and exits. I am using CriticalSection, to make sure only one thread access the ThreadFunc. If I dont give Sleep function, I see thread exits and then It will print 'Hello World' . Is the mother thread that causes this problem. please correct me.
Code:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
CRITICAL_SECTION cs;
DWORD WINAPI ThreadFunc(LPVOID lpParam) {
EnterCriticalSection(&cs);
printf("HelloWorld= %d\n.",*(DWORD*)lpParam );
LeaveCriticalSection(&cs);
return 0;
}
VOID main( VOID ) {
DWORD dwThreadId;
HANDLE hThread[20];
int i,n;
for(i=0;i<20;i++){
hThread[i] = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
&dwThreadId, // argument to thread function
CREATE_SUSPENDED, // use default creation flags
&dwThreadId);
//Sleep(20);
}
for(n=0;n<20;n++){
InitializeCriticalSection(&cs);
if (hThread[n] == NULL){
printf( "CreateThread failed." );
}
else {
EnterCriticalSection(&cs);
ResumeThread(hThread[n]);
Sleep(0);//Resume the thread from suspended state
LeaveCriticalSection(&cs);
CloseHandle( hThread[n] );
printf("Thread Exiting \n");
DeleteCriticalSection(&cs);
}
}
}
Is the mother thread that causes the error. please correct me.
-
> InitializeCriticalSection(&cs);
Try doing this just the ONCE
Perferably before any thread tries to use it
> printf("HelloWorld= %d\n.",*(DWORD*)lpParam );
Put the \n at the end of the string
I could say something about your call to createthread, but that would spoil the fun...
-
I could write a long thread, but I thought this would be easier...
Code:
#include <windows.h>
#include <stdio.h>
#define NUM_THREADS 200
CRITICAL_SECTION cs;
DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
EnterCriticalSection(&cs);
printf("Hello World, I'm thread# %d\n", (int)lpParam);
LeaveCriticalSection(&cs);
return 0;
}//ThreadFunc
int main()
{
DWORD dwThreadId;
HANDLE hThread[NUM_THREADS];
int n;
InitializeCriticalSection(&cs);
// create all the threads
for (n = 0; n < NUM_THREADS; n++)
{
hThread[n] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)n, 0, &dwThreadId);
if (hThread == NULL)
fprintf(stderr, "Failed to create thread# %d", n);
}//for
// wait for all the threads to exit
for (n = 0; n < NUM_THREADS; n++)
{
if (hThread[n] != NULL)
WaitForSingleObject(hThread[n], INFINITE);
}//for
DeleteCriticalSection(&cs);
return 0;
}//main