1.要求定義一個全局變量char buf="1234567",創建兩個線程,不考慮退出條件。
a.A線程循環打印buf字符串,
b.B線程循環倒置buf字符串,即buf中本來存儲1234567,倒置后buf中存儲7654321.B線程中不打印!!
c.倒置不允許使用輔助數組。
d.要求A線程打印出來的結果只能為1234567或者 7654321不允許出現76345217234567等亂序情況
e.不允許使用sleep函數
f.分析出現錯誤的原因。
錯誤原因:主進程和分支進程是并發執行的,無法預測誰先誰后。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>char buf[] = "1234567";
int len = sizeof(buf);void* overtrun(void* arg) //void* arg = (void*)buf
{int i=0,j=len;char temp;while(1){for(i=0,j=len-2; i < j; i++,j--){temp = ((char*)arg)[i];((char*)arg)[i] = ((char*)arg)[j];((char*)arg)[j] = temp;}pthread_exit(NULL);} return arg;
}int main(int argc, const char *argv[])
{
// char* pb = buf;pthread_t tid;pthread_create(&tid, NULL, overtrun, (void*)buf);printf("%d\n",len);while(1){int i,j;for(i=0; i<len-1; i++){printf("%c",buf[i]);}putchar(10); }pthread_join(tid,NULL);return 0;
}
2.完成圖片拷貝,要求一個線程拷貝一半,另一個線程拷貝另一半。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>typedef struct
{FILE* fop;FILE* fop_w;long size;
}Info;void* copy(void* arg) //void* arg = (void*)&msg
{char b;int count=0,i=0;fseek( ((Info*)arg)->fop, (((Info*)arg)->size/2),SEEK_SET);fseek( ((Info*)arg)->fop_w, (((Info*)arg)->size/2),SEEK_SET);for(i; i< (((Info*)arg)->size/2); i++){fscanf( ((Info*)arg)->fop, "%c", &b);fprintf( ((Info*)arg)->fop_w,"%c",b);count++;// printf("分支線程復制:%d\n",count);}printf("分支線程復制了%d個\n",count);pthread_exit(NULL);return arg;
}int main(int argc, const char *argv[])
{Info msg;msg.fop = fopen("./cq.jpg","r");if(msg.fop == NULL){perror("fop");return -1;}msg.fop_w = fopen("./f.jpg","w");if(msg.fop_w == NULL){perror("fop_w");return -1;}fseek(msg.fop, 0, SEEK_END);msg.size = ftell(msg.fop);printf("大小:%ld\n",msg.size);pthread_t tid;pthread_create(&tid, NULL, copy, (void*)&msg);char c;int count=0,i=0;printf("開始\n");fseek(msg.fop, 0,SEEK_SET);fseek(msg.fop_w, 0,SEEK_SET);for(i; i<msg.size/2; i++){fscanf(msg.fop,"%c",&c);fprintf(msg.fop_w,"%c",c);count++;// printf("主線程復制:%d\n",count);}printf("主線程復制了%d個\n",count);pthread_join(tid,NULL);if(fclose(msg.fop_w) < 0){perror("fclose_fop_w");return -1;}if(fclose(msg.fop) < 0 ){perror("fclose_fop");return -1;}return 0;
}