I am for my own amusement tinkering with this piece of code:
#include <windows.h>
#include <process.h>
#include <stdlib.h>
#include <stdio.h>
void print_message(void *param)
{
int thread_counter = *((int*)param);
printf("Thread #%i\r\n", thread_counter);
_endthreadex(0);
}
int main()
{
unsigned thread_ID;
HANDLE thread_handle;
int thread_count = 10;
HANDLE thread_handles[thread_count];
for(int i = 0; i < thread_count; i++)
{
thread_handles[i] = (HANDLE)_beginthreadex(NULL, 0, &print_message, &i, 0, &thread_ID);
thread_handle = thread_handles[i];
}
WaitForMultipleObjects(thread_count, thread_handles, TRUE, INFINITE);
return EXIT_SUCCESS;
}
a
Output
Thread #8
Thread #10
Thread #10
Thread #10
Thread #10
Thread #10
Thread #10
Thread #10
Thread #10
Thread #10
I think the problem is that I am passing a reference to variable i, and the variable i is being incremented in the for loop while the threads are using/manipulating this reference.
How do i avoid the race condition, and pass the value of variable i to the thread function?
I would also like to pass strings/char arrays to the thread function, but I do not seem to understand how to do this.
I am using the Tiny C Compiler (TCC) on Windows 10