8.6日作业
逆置打印
#include "iohead.h"
//负责打印
char str[128]="hello";void *callback1(void *arg1)
{while(1){puts(str); putchar(10);sleep(3);}
}
//负责逆置
void *callback2(void *arg2)
{sleep(1);while(1){int len=strlen(str);for(int i=0,j=len-1;i<len/2;++i,--j){char temp=str[i];str[i]=str[j];str[j]=temp;}sleep(1);}
}int main(int argc, const char *argv[])
{ //创建第一个分支pthread_t thread1;if(pthread_create(&thread1,NULL,callback1,NULL)!=0){printf("pthread_create error");return -1;}//第二个分支pthread_t thread2;if(pthread_create(&thread2,NULL,callback2,NULL)!=0){printf("pthread_create error");return -1;}pthread_join(thread1,NULL);pthread_join(thread2,NULL);while(1);return 0;
}
#include "iohead.h"
void *callback(void* arg)
{//打开文件FILE *fp=fopen("./file","r");FILE *fp_w=fopen("./myfile","w");//光标偏移末尾,计算文件大小fseek(fp,0,SEEK_END);long len=ftell(fp);fseek(fp,0,SEEK_SET);fseek(fp_w,0,SEEK_SET);char buf;for(int i=0;i<len/2;i++){//从file中读取写入bufif(1>fread(&buf,1,1,fp)){break;}//buf里的内容写入fp_wfwrite(&buf,1,1,fp_w);}//关闭文件if(EOF==fclose(fp)){printf("文件关闭失败");}if(EOF==fclose(fp_w)){printf("文件关闭失败");}return NULL;
}
void *callback1(void* arg)
{//打开文件FILE *fp=fopen("./file","r");FILE *fp_w=fopen("./myfile","w");//光标偏移末尾,计算文件大小fseek(fp,0,SEEK_END);long len=ftell(fp);fseek(fp,len/2,SEEK_SET);fseek(fp_w,len/2,SEEK_SET);char buf;for(int i=len/2;i<len;i++){//从file中读取写入bufif(1>fread(&buf,1,1,fp)){break;}//buf里的内容写入fp_wfwrite(&buf,1,1,fp_w);}//关闭文件if(EOF==fclose(fp)){printf("文件关闭失败");}if(EOF==fclose(fp_w)){printf("文件关闭失败");}return NULL;
}
int main(int argc, const char *argv[])
{pthread_t thread,thread1;//创建一个线程使用threadif(0!=pthread_create(&thread,NULL,callback,NULL)){return -1;}//创建第二个线程使用thread1if(0!=pthread_create(&thread1,NULL,callback,NULL)){return -1;}pthread_detach(thread);pthread_detach(thread1);while(1);return 0;