1. 要求创建两个线程,以及一个全局变量,char str[] = "123456";要求如下:
1)一个线程专门用于打印str;
2)另外一个线程专门用于倒置str字符串,不使用辅助数组。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
char str[] = "123456";
void* callback(void* arg)
{
char* star = str;
char* end = str;
while(*end!='\0'){
end++;
}
end--;
while(end>star){
*star ^= *end;
*end ^= *star;
*star ^= *end;
end--;
star++;
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
if(pthread_create(&tid,NULL,callback,NULL)!=0)
{
perror("pthread");
}
sleep(1);
printf("%s\n",str);
return 0;
}
2. 要求用线程拷贝一张图片,一个线程拷贝前半部分,另一个线程拷贝后半部
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
int f1 = 0;
int f2 = 0;
void* callback(void* arg)
{
FILE* fp;
FILE* fn;
fp = fopen((char*)arg,"r");
if(fp<0){
perror("open3");
return NULL;
}
fn = fopen("zyl.png","a+");
if(fn<0){
perror("open4");
return NULL;
}
long num = fseek(fp,0,SEEK_END);
num = ftell(fp);
fseek(fp,num/2,SEEK_SET);
fseek(fn,num/2,SEEK_SET);
char arr[1000] ="";
size_t res;
while((res = fread(arr,1,sizeof(arr),fp))!=0){
fwrite(arr,res,1,fn);
bzero(arr,res);
}
printf("后半部分拷贝完毕!\n");
f2 = 1;
fclose(fp);
fclose(fn);
}
int main(int argc, const char *argv[])
{
FILE* fp;
FILE* fn;
fp = fopen(argv[1],"r");
if(fp<0){
perror("open1");
return -1;
}
fn = fopen("zyl.png","w");
if(fn<0){
perror("open2");
return -1;
}
fseek(fp,0,SEEK_END);
long num = ftell(fp);
pthread_t tid;
if(pthread_create(&tid,NULL,callback,(void*)argv[1])!=0){
perror("pthread");
}
fseek(fp,0,SEEK_SET);
fseek(fn,0,SEEK_SET);
char a ='0';
for(int i=0;i<num/2;i++){
fread(&a,1,1,fp);
fwrite(&a,1,1,fn);
}
printf("前半段拷贝完毕!\n");
f1 = 1;
fclose(fp);
fclose(fn);
sleep(1);
// while(!(f1&&f2));
return 0;
}