#include
#include
#include
#define false 0
#define ture 1
int flag[2];
static int a = 1;
int turn;
void *p0(){
while (ture){
flag [0]=ture; //this means I want the critical section
turn = 0;//this means i have the chance.
while (flag[1]&&turn==0);//this is for busywaiting ,until the other is not intersted any more.
a--;//I am in!
flag[0]=false;//I am not interested any more.
printf ("这是第一个线程a=%d\n",a);// not about critical section
sleep(1);//I block
}
}
void *p1(){
while (ture){
flag[1]=ture ;
turn = 1;
while (flag[0]&&turn==1);
a++;//linjiequ
flag[1]=false ;
printf ("这是第二个线程a=%d\n",a);
sleep(1);//other code
} // result is the first thread a=o then second thread a=1
}
int main(){
flag[0]=false;
flag[1]=false;
int err1,err2;
pthread_t id1,id2;
err1=pthread_create(&id2, NULL, p1, NULL);
err2=pthread_create(&id1, NULL, p0, NULL);//while create system do not run the p0/p1 body.
pthread_join( id2, NULL);//let id1 runs
pthread_join( id1, NULL);//let id1 runs and main waits
}
我不理解main里到底是怎么运行的,create了两个进程以后第一个join就让id2进程运行嘛,对应着让p1运行 所以这第一下应该就可以打出这是第二个进程a=2然后挂起再运行进程id1嘛,id1又打出这是第一个进程a=1 接着再id2 id1一直循环下去。但是编译运行的结果却是先打印
这是第一个进程a=0 然后是这是第二个进程a=1 然后循环下去 甚至把其中的一个join给//,结果也还是一样 可是不是应该有一个进程就得不到机会运行了吗?所以问题来了.
1 为什么是这个顺序?
2 为什么//一个join以后还是有两个进程运行
启动顺序跟你create, join顺序都无关,它是系统自由调度的。哪种顺序都可能。这里不存在一个固定顺序
回答你第二个问题:
pthread-join是等待线程退出时, 负责回收线程资源的. 你是否注释掉, 不影响两个子线程的正常运行.