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日

悬赏问题

  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载