定义一个全局变量char buf[]=”1234567”,创建两个线程,不考虑退出条件。
线程一循环打印buf字符串。
线程二循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321,不打印。
线程一打印出来的结果只能是1234567或7654321.
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<pthread.h>
#include<string.h>
char buf[]="1234567";
void* callBack1(void* arg)
{
while(1){
printf("%s\n",buf);
sleep(0.5);
}
}
void* callBack2(void* arg)
{
intnum=strlen(buf);
inti=0;
inttemp=0;
while(1){
for(i=0;i<num/2;i++){
temp=buf[i];
buf[i]=buf[num-1-i];
buf[num-1-i]=temp;
}
sleep(1);
}
}
int main(int argc, const char *argv[])
{ pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,callBack1,NULL)!=0){
fprintf(stderr,"pthread_createerror");
return-1;
}
if(pthread_create(&tid2,NULL,callBack2,NULL)!=0){
fprintf(stderr,"pthread_createerror");
return-1;
}
pthread_detach(tid1);
pthread_join(tid2,NULL);
return0;
}