拷贝图片
为什么出错:循环打印全局变量,c中的数据还没来得及换,时间片就切换到打印。改正如下,定义一个信号去判断何时打印
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
int a = 0;
char buf[] = "1234567";
void* callback1(void* arg)
{
while(1)
{
if(0==a)
printf("%s\n",buf);
a=1;
}
pthread_exit(NULL);
}
void* callback2(void* arg)
{
int i=0,j=0;
char c;
while(1)
{
if(1==a)
for(i=0,j=strlen(buf)-1;i<j;i++,j--)
{
c = buf[i];
buf[i] = buf[j];
buf[j] = c;
}
a=0;
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//创建两个线程
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callback1,NULL)!=0)
{
printf("create success\n");
return -1;
}
if(pthread_create(&tid2,NULL,callback2,NULL)!=0)
{
printf("create success\n");
return -1;
}
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}