zpwpal 2014-11-02 10:40 采纳率: 0%
浏览 1651

大学狗linux线程同步与互斥求助呀

#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以后还是有两个进程运行

  • 写回答

2条回答 默认 最新

  • oyljerry 2014-12-04 06:40
    关注

    启动顺序跟你create, join顺序都无关,它是系统自由调度的。哪种顺序都可能。这里不存在一个固定顺序

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器