#include <stdio.h>
#include <string.h>
#include <pthread.h>
void* some_func (void* arg)
{
int num = *(int*)arg;
int i = 10;
for (; i > 0; i--)
{
usleep (1); //to give other thread chances to cut in
printf ("This is from the thread %d\n", num);
}
}
int main()
{
pthread_t thread[3];
int index =0;
for (; index <3 ; index++)
{
if (pthread_create (thread+index, NULL, some_func, &index ))
{
usleep(10);
printf ("something is wrong creating the thread");
}
}
pthread_join ( thread[0], NULL);
pthread_join ( thread[1], NULL);
pthread_join ( thread[2], NULL);
return 0;
}
It was supposed to output "This is from thread x", where x = 0 or 1 or 2, and show output alternatively. However, I could only get 2 and 3.
Since 3 is undefined in the original design, I believe that after the thread for index=2 is created, the index has already incremented to 3. Therefore, arg pointed to a value of 3 and then num is assigned to be 3.
In my code, I passed the address of variable index--which should instead be the value of index--to the function.
The correct way should then be (line 22) if (pthread_create (thread+index, NULL, some_func, (void*) index))
and line 7, just int num = (int) arg;