I was trying to create a function in C which would let me pass a character as its argument when using the CreateThread function.
It works for the most part, the thread is created and prints a character. The problem is, it many of the threads don’t print the character they are supposed to print, and instead print the last one. I assume it has something to do with how the character is passed on to the function, or perhaps the synchronization.
Here is the code:
#define LETTERS "abcdefghij"
DWORD WINAPI threadFunc(LPVOID param) {
HANDLE sem = OpenSemaphore(SEMAPHORE_ALL_ACCESS, TRUE, (LPCWSTR)"sem");
PCHAR name;
name= (PCHAR)param;
printf("I'm a thread: %cn", *name);
fflush(stdout);
ReleaseSemaphore(sem, 1, NULL);
return 1;
}
int main()
{
DWORD(*f)(LPVOID);
f = threadFunc;
HANDLE sem = CreateSemaphore(NULL, 0, 10, (LPCWSTR)"sem");
int i;
DWORD name;
CHAR nameOfThread;
for (i = 0;i < 10;i++) {
nameOfThread= LETTERS[i];
CreateThread(NULL, 0, f, &nameOfThread, 0, &name);
}
for (i = 0;i < 10;i++) {
WaitForSingleObject(sem, INFINITE);
}
printf("I'm the processn");
}
And here are the results of executing it:
I'm a thread: g
I'm a thread: h
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm a thread: j
I'm the process
Any help would be appreciated.