multithread in C: changing values

Greetings!

I am now studying multithread programming and wrote a sample code. However, it does not do the correct thing:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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.

How can I get the desired output?

Any suggestions would be appreciated!
Never mind. This thread solves my question.

http://stackoverflow.com/questions/4221019/how-to-pass-parameters-to-a-thread-in-c-multithreading-properly

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;
Topic archived. No new replies allowed.