m0_70291963 2022-04-28 19:03 采纳率: 100%
浏览 24
已结题

C语言,Linux关于多线程的问题

img

img


这两张图片是同一个代码,为什么这个子线程有时候会不运行呢?
代码:#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
//线程函数
typedef struct{
int t;
}MY_ARGS;
int s1,s2;
void test1(void args1)
{
MY_ARGS
my_args = (MY_ARGS
) args1;
int i=0;
while(1)
{
if(s1==s2)
{
pthread_exit(NULL);
}
printf("test1= %d\n", i++);
my_args -> t = i-1;
sleep(2);

    }

}

void test2(void args2)
{
int j=20;
MY_ARGS
my_args = (MY_ARGS
) args2;
while(1)
{
if(s1==s2)
{
pthread_exit(NULL);
}
printf(" test2= %d\n",j--);
my_args -> t = j+1;

            sleep(3);
           
    }

}

int main ()
{
MY_ARGS args1 = {0};
MY_ARGS args2 = {20};

pthread_t pId1;
pthread_t pId2;
int i,ret1,ret2;
//创建子线程,线程id为pId
ret1 = pthread_create(&pId1,NULL,test1,&args1);
ret2 = pthread_create(&pId2,NULL,test2,&args2);
if(ret1 != 0)
{
printf("create pthread error!\n");
exit(1);
}

if(ret2 != 0)
{
printf("create pthread error!\n");
exit(1);
}

for(i=0;i<60;i++)
{
s1=args1.t;
s2=args2.t;
if(s1==s2)
{
for(int j =10;j>0;j--)
{
printf("倒计时3=%d\n",j);
sleep(1);
}
break;
}
printf("地%d秒,倒计时1=%d,倒计时2=%d\n",i+1,s1,s2);
sleep(1);
}
pthread_join(pId1,NULL);
pthread_join(pId2,NULL);
return 0;
}

  • 写回答

1条回答 默认 最新

  • 柒号华仔 2022年度博客之星评选前沿技术领域TOP 1 2022-04-28 20:35
    关注

    多线程调用全局变量需要加锁

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 7月6日
  • 已采纳回答 6月28日
  • 创建了问题 4月28日

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备