pthread 函式庫提供了四個核心介面:
#include <pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
void pthread_exit(void *retval);
int pthread_join(pthread_t *thread, void **thread_return);
pthread_create 用來建立執行緒:thread 回傳執行緒 ID,attr 指定建立屬性(傳 NULL 即使用預設值),start_routine 是執行緒啟動後要跑的函式指標,arg 是傳給該函式的唯一參數。
pthread_exit 類似 exit,用來結束執行緒、釋放資源並阻塞,直到其他執行緒以 pthread_join 等待它,此時會把 retval 的值傳給 thread_return。正因為它會釋放所有資源,retval 不可指向函式的區域變數。
pthread_join 的作用與 wait 相同,用來等待指定執行緒結束。
實務上常需要批次備份檔案,下面這支程式會把當前目錄下所有檔案複製一份,副檔名加上 .bak,每個檔案由一個執行緒負責。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <dirent.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#define BUFFER 512
struct copy_file {
int infile;
int outfile;
};
void *copy(void *arg)
{
int infile, outfile;
int bytes_read, bytes_write, *bytes_copy_p;
char buffer[BUFFER], *buffer_p;
struct copy_file *file = (struct copy_file *)arg;
infile = file->infile;
outfile = file->outfile;
/* 執行緒結束時會釋放所有變數空間,因此必須自行配置記憶體 */
if ((bytes_copy_p = (int *)malloc(sizeof(int))) == NULL) pthread_exit(NULL);
bytes_read = bytes_write = 0;
*bytes_copy_p = 0;
while ((bytes_read = read(infile, buffer, BUFFER)) != 0) {
if ((bytes_read == -1) && (errno != EINTR)) break;
else if (bytes_read > 0) {
buffer_p = buffer;
while ((bytes_write = write(outfile, buffer_p, bytes_read)) != 0) {
if ((bytes_write == -1) && (errno != EINTR)) break;
else if (bytes_write == bytes_read) break;
else if (bytes_write > 0) {
buffer_p += bytes_write;
bytes_read -= bytes_write;
}
}
if (bytes_write == -1) break;
*bytes_copy_p += bytes_read;
}
}
close(infile);
close(outfile);
pthread_exit(bytes_copy_p);
}
int main(int argc, char **argv)
{
pthread_t *thread;
struct copy_file *file;
int byte_copy, *byte_copy_p, num, i, j;
char filename[BUFFER];
struct dirent **namelist;
struct stat filestat;
/* 取得當前路徑下所有檔案(含目錄)數量 */
if ((num = scandir(".", &namelist, 0, alphasort)) < 0) {
fprintf(stderr, "Get File Num Error:%s\n\a", strerror(errno));
exit(1);
}
if (((thread = (pthread_t *)malloc(sizeof(pthread_t) * num)) == NULL) ||
((file = (struct copy_file *)malloc(sizeof(struct copy_file) * num)) == NULL)) {
fprintf(stderr, "Out Of Memory!\n\a");
exit(1);
}
for (i = 0, j = 0; i < num; i++) {
memset(filename, '\0', BUFFER);
strcpy(filename, namelist[i]->d_name);
if (stat(filename, &filestat) == -1) {
fprintf(stderr, "Get File Information:%s\n\a", strerror(errno));
exit(1);
}
/* 忽略目錄 */
if (!S_ISREG(filestat.st_mode)) continue;
if ((file[j].infile = open(filename, O_RDONLY)) < 0) {
fprintf(stderr, "Open %s Error:%s\n\a", filename, strerror(errno));
continue;
}
strcat(filename, ".bak");
if ((file[j].outfile = open(filename, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
fprintf(stderr, "Creat %s Error:%s\n\a", filename, strerror(errno));
continue;
}
/* 建立執行緒進行複製 */
if (pthread_create(&thread[j], NULL, copy, (void *)&file[j]) != 0)
fprintf(stderr, "Create Thread[%d] Error:%s\n\a", i, strerror(errno));
j++;
}
byte_copy = 0;
for (i = 0; i < j; i++) {
/* 等待執行緒結束 */
if (pthread_join(thread[i], (void **)&byte_copy_p) != 0)
fprintf(stderr, "Thread[%d] Join Error:%s\n\a", i, strerror(errno));
else {
if (byte_copy_p == NULL) continue;
printf("Thread[%d] Copy %d bytes\n\a", i, *byte_copy_p);
byte_copy += *byte_copy_p;
/* 釋放 copy 函式中配置的記憶體 */
free(byte_copy_p);
}
}
printf("Total Copy Bytes %d\n\a", byte_copy);
free(thread);
free(file);
exit(0);
}
程式的重點有兩個:一是執行緒結束時會回收其堆疊與區域變數,因此需要回傳的統計值必須用 malloc 配置在堆上;二是在主執行緒用 pthread_join 逐一等待並 free 掉那塊記憶體,否則就是記憶體洩漏。編譯時記得加上 -lpthread。