This is my code. It's very simple.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *func(void *arg)
{
printf("ID=%d\n", *(int*)arg);
pthread_exit(NULL);
}
int main()
{
pthread_t pt[4];
int i;
for (i = 0; i < 4; i++)
{
int temp = i;
pthread_create(&pt[i], NULL, func, (void*)&temp);
}
sleep(1);
return 0;
}
I compiled it:
gcc p_test.c -lpthread
I ran it. It printed 2 2 3 3
. I ran it again. It printed 2 3 3 2
.
My problem is:
Why was 2
or 3
printed twice?
Why didn't it print 1 3 2 0
or any other results?
The major problem here is that you're taking the address of the local variable temp
, and then using that pointer outside the scope of the variable - as soon as you exit one iteration of the loop, your pointer to temp
becomes invalid and you must not dereference it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With