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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?