haohaode32 2019-10-23 09:35 采纳率: 0%
浏览 322

linux下父子线程交替执行,有一部分不输出

#include<stdlib.h>
#include<pthread.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
const int count=15;
int flag;
void* even(void * a){
    int i;
    for (i = 1; i < count; i+=2)
    {
        if (flag==0)
        {
            flag=1;
            printf("child thread is %d\n",i);
        }
        sleep(1);
    }
    return 0;
}

int main(int argc, char const *argv[])
{
    int err;
    int * rev;
    pthread_t tid;
    err=pthread_create(&tid,NULL,even,NULL);
    if(err!=0){
        printf("create pthread failure\n");
        return 0;
    }
    for (int b = 0; b < count; b+=2)
    {
        if (flag==1)
        {
        flag=0;
        printf("main thread is %d\n",b);
        }
        sleep(1);
    }
    pthread_exit(rev);
}

上面的程序让父子线程分别交替打印偶数和奇数,结果会交替,但是有一部分数没有输出。
图片说明
请大家帮忙看看上面的问题在哪里

  • 写回答

1条回答 默认 最新

  • J4cks0n 2019-10-23 16:00
    关注

    //多线程当然要加锁
    //for那里i+=2或b+=2部分逻辑自己好好理解下
    //变量记得赋初始值

    #include<stdlib.h>
    #include<pthread.h>
    #include<stdio.h>
    #include<string.h>
    #include<unistd.h>
    
    pthread_mutex_t mutex ;  
    const int count=15;
    int flag = 1;
    void* even(void * a)
    {
        int i;
        for (i = 1; i < count; )
        {
            if (flag==0)
            {
                pthread_mutex_lock(&mutex);
                flag=1;
                printf("child thread is %d\n",i);
                i+=2;
                pthread_mutex_unlock(&mutex);
            }
            sleep(1);
        }
        return 0;
    }
    
    int main(int argc, char const *argv[])
    {
        pthread_t tid; 
        pthread_create(&tid,NULL,even,NULL);
    
        pthread_mutex_init(&mutex,NULL); 
    
    
        for (int b = 0; b < count; )
        {
            if (flag==1)
            {
                pthread_mutex_lock(&mutex);
                flag=0;
                printf("main thread is %d\n",b);
                b+=2;
                pthread_mutex_unlock(&mutex);
            }
            sleep(1);
        }
        pthread_join(tid,NULL);
    
        pthread_mutex_destroy(&mutex);  
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog