#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int counter;
void *thr_fun(void *arg)
{
for(int i = 0; i < 10; i++) {
printf("%lu %d\n", pthread_self(), ++counter);
}
return NULL;
}
int main()
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, thr_fun, NULL);
pthread_create(&tid2, NULL, thr_fun, NULL);
sleep(5);
return 0;
}
某一次的输出结果:
140031959435008 1
140031959435008 3
140031959435008 4
140031959435008 5
140031959435008 6
140031959435008 7
140031959435008 8
140031959435008 9
140031959435008 10
140031959435008 11
140031951042304 2
140031951042304 12
140031951042304 13
140031951042304 14
140031951042304 15
140031951042304 16
140031951042304 17
140031951042304 18
140031951042304 19
140031951042304 20
不是多线程嘛,为啥这输出结果先是第一个进程全部打印完,
然后打印第二个进程的结果;
counter = 2 时的++ 明显是第二个进程执行的,
那为啥后面的就是等第一个线程执行完再执行第二个线程;