NCHU逸尘 2020-06-28 13:59 采纳率: 33.3%
浏览 704
已结题

linux c 多线程访问全局变量

#include<pthread.h>
#include<stdio.h>
int i = 1;
void thread1(void * data){
        i++;
}
void thread2(void * data){
        --i;
}
int main(){
        pthread_t t[2];
        pthread_create(&t[0], NULL, thread1, NULL);
        pthread_create(&t[1], NULL, thread2, NULL);
        sleep(2);
        printf("i = %d\n",i);
        return 0;
}

最终结果,i 应该等于0或1或2,结果是不确定的。但是我反复执行,结果总是1,还请大佬指点一下。我的操作系统是ubuntu18.04.2 LTS,gcc版本是7.5.0。

  • 写回答

2条回答 默认 最新

  • J4cks0n 2020-06-28 16:45
    关注

    thread里的操作执行时间过短,主线程里的延时过长,在主线程退出前,两个子线程都执行完了

    评论

报告相同问题?