关于输出结果的一些疑问(有关线程)
#include <stdio.h>#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <pthread.h>
#define NT 16
pthread_mutex_t mutt;
#define A 3
#define B 4
#define C 5
int answer = 0;
void *worker(int *p);
int main(int arg, char *argv[])
{
pthread_t thid[NT];
int id[NT];
int i;
for(i=0;i<NT;i++)
id[i] = i;
pthread_mutex_init(&mutt, 0);
for(i=0;i<NT;i++)
pthread_create(&thid[i], 0, (void *) worker, (void *) &id[i]);
for(i=0;i<NT;i++)
pthread_join(thid[i], 0);
printf("%d\n", answer);
}
void *worker(int *p)
{
int tmp;
int id;
id = *p;
if(id == 0){ /* adder */
//tmp = answer;
printf("%d\n",id);
tmp = answer + C;
answer = tmp;
} else {
printf("%d\n",id);
tmp = A;
tmp = tmp * B;
answer = tmp;
}
return;
}
下面是输出结果
*********1
0
2
3
4
7
8
6
5
10
9
11
12
13
14
15
12
我在worker函数中每次都输出变量id,但是为什么输出结果不是0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15?谢谢大家了