2023-5-9作业
要求定义一个全局变量 char buf[] = "1234567",创建两个线程,不考虑退出条件。
A线程循环打印buf字符串,
B线程循环倒置buf字符串,即buf中本来存储1234567,倒置后buf中存储7654321. 不打印!!
倒置不允许使用辅助数组。
要求A线程打印出来的结果只能为 1234567 或者 7654321 不允许出现7634521 7234567
不允许使用sleep函数
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/wait.h>
#include<pthread.h>
#include<time.h>
char buf[]="1234567"; //全局变量
void *callBlack(void *arg) //分支线程 循环打印
{
int i=0;
while(i<7)
{printf("%d ",buf[i]-48);i++;}putchar(10);
char *str=(char*)malloc(12);
strcpy(str,"1");
pthread_exit(str); //退出线程传递线程退出的值
}
int main(int argc,const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,callBlack,NULL)!=0)
{fprintf(stderr,"pthread_create file line:%d\n",__LINE__);return -1;}
int len=strlen(buf);
int i,j;char temp;void *ptr=NULL;
for(i=0,j=len-1;j>=i;i++,j--) //循环倒置
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
free(str);
str=NULL;
pthread_join(tid,&ptr); //阻塞等待分支线程接收推出的值。
}