1. 程式人生 > 其它 >Linux中多執行緒,同步將一個檔案內容複製到另一個檔案裡面

Linux中多執行緒,同步將一個檔案內容複製到另一個檔案裡面

int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *), void *arg);
int pthread_join (pthread_t tid, void ** status);

pthread_create用於建立一個執行緒,成功返回0,否則返回Exxx(為正數)。

  • pthread_t *tid:執行緒id的型別為pthread_t,通常為無符號整型,當呼叫pthread_create成功時,通過*tid指標返回。
  • constpthread_attr_t *attr:指定建立執行緒的屬性,如執行緒優先順序、初始棧大小、是否為守護程序等。可以使用NULL來使用預設值,通常情況下我們都是使用預設值。
  • void*(*func) (void*):函式指標func,指定當新的執行緒建立之後,將執行的函式。
  • void*arg:執行緒將執行的函式的引數。如果想傳遞多個引數,請將它們封裝在一個結構體中。

pthread_join用於等待某個執行緒退出,成功返回0,否則返回Exxx(為正數)。

  • pthread_t tid:指定要等待的執行緒ID
  • void** status:如果不為NULL,那麼執行緒的返回值儲存在status指向的空間中(這就是為什麼status是二級指標的原因!這種才引數也稱為“值-結果”引數)。

#include <stdio.h>
#include <stdlib.h>
#include 
<string.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #define N 3 //每次讀取的字元數 /* 按順序輸出我是1我是2不會亂序。 */ sem_t rt, dt;//定義兩個訊號量 char buf[N] = {0}; int flag = 0; int fd_1,fd_2; void *fun_1(void
*arg)//執行緒1 { char *p = (char *)arg; while(1) { //申請資源,如果沒有資源,則程式阻塞休眠,如果有資源,資源數-1,程式繼續執行 sem_wait(&rt); // int red = read(fd_1,buf,sizeof(buf)); if(-1 == red) { perror("read"); break; } if(N > red) { flag = 1; sem_post(&dt); break; } puts(p); //釋放資源,對應資源+1 sem_post(&dt); } } void *fun_2(void *arg)//執行緒2 { char *p = (char *)arg; while(1){ //申請資源,如果沒有資源,則程式阻塞休眠,如果有資源,資源數-1,程式繼續執行 sem_wait(&dt); // int wre = write(fd_2,buf,strlen(buf)); if(-1 == wre) { perror("write"); break; } if(1 == flag) { break; } puts(p); //釋放資源,對應資源+1 sem_post(&rt); } } int main()//main函式內為主執行緒,主執行緒在執行子執行緒才能正常執行。 { fd_1 = open("one.c",O_RDONLY); fd_2 = open("two.c",O_RDWR | O_CREAT | O_TRUNC,0777); if(-1 == fd_1) { perror("open one"); return -1; } if(-1 == fd_2) { perror("open two"); return -1; } pthread_t tid_1; pthread_t tid_2; if(0 != pthread_create(&tid_1, NULL, fun_1, "I am one!")){ perror("pthread_create1"); return -1; } if(0 != pthread_create(&tid_2, NULL, fun_2, "I am two!")){ perror("pthread_create1"); return -1; } //初始化訊號量 if(0 != sem_init(&rt, 0, 1))//給rt分配1個資源 { perror("sem_init"); return -1; } if(0 != sem_init(&dt, 0, 0))//給dt分配0個資源 { perror("sem_init"); return -1; } //回收讀執行緒 pthread_join(tid_1, NULL);//阻塞直到tid_1執行緒結束 //回收寫執行緒 pthread_join(tid_2, NULL);//阻塞直到tid_2執行緒結束 printf("複製完成!"); close(fd_1); close(fd_2); }