这两张图片是同一个代码,为什么这个子线程有时候会不运行呢?
代码:#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;
}