I'm learning about POSIX threads right now, but I guess this is just a general question on multithreading, so I hope that anyone can help me. I have this example from the book that I am working on which demonstrates a race condition:
void *thread_main(void *thread_number) {
printf("In thread number %d.\n", *(int *)thread_number);
}
void main() {
int i = 0;
pthread_t thread;
for( i = 0; i < 10; i++ ) {
printf("Creating thread %d.\n");
pthread_create(&thread, 0, thread_main, &i);
printf("Created thread %d.\n");
}
}
There are a few things I don't understand about this. First, "In thread number 5." gets printed many times even though it's not supposed to be in thread number 5. In the book, the example shows thread 8 getting printed many times. I also don't understand the part that says *(int *)thread_number
. I tried changing this to just thread_number, but that just gave me strange numbers over and over again.
The book doesn't really explain this. Can somebody give me a clear explanation of what's going on here? I don't understand why it doesn't print something like:
> Creating thread 1.
> In thread number 1.
> Created thread 1.
> Creating thread 2.
> In thread number 2.
> Created thread 2.
I know that because it's multithreaded the "In thread number x." part will come at different times, but I really don't get why there isn't exactly 10 "In thread number x" with one line for each thread I created!
~desi