前言:linux下執行緒的建立
介紹在linux下執行緒的建立和基本的使用. linux下的執行緒是乙個非常複雜的問題,由於我對執行緒的學習不時很好,我在這裡只是簡單的介紹執行緒的建立和基本的使用,關於執行緒的高階使用(如執行緒的屬性,執行緒的互斥,執行緒的同步等等問題)可以參考我後面給出的資料. 現在關於執行緒的資料在網路上可以找到許多英文資料,後面我羅列了許多鏈結,對執行緒的高階屬**興趣的話可以參考一下. 等到我對執行緒的了解比較深刻的時候,我回來完成這篇文章.如果您對執行緒了解的詳盡我也非常高興能夠由您來完善.
先介紹什麼是執行緒.我們編寫的程式大多數可以看成是單執行緒的.就是程式是按照一定的順序來執行.如果我們使用執行緒的話,程式就會在我們建立線成的地方分叉,變成兩個"程式"在執行.粗略的看來好象和子程序差不多的,其實不然.子程序是通過拷貝父程序的位址空間來執行的.而執行緒是通過共享程式**來執行的,講的通俗一點就是執行緒的相同的**會被執行幾次.使用執行緒的好處是可以節省資源,由於執行緒是通過共享**的,所以沒有程序排程那麼複雜.
執行緒的建立和使用
執行緒的建立是用下面的幾個函式來實現的.
#include
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 *thread,void **thread_return);
pthread_create建立乙個執行緒,thread是用來表明建立執行緒的id,attr指出執行緒建立時候的屬性,我們用null來表明使用預設屬性.start_routine函式指標是執行緒建立成功後開始執行的函式,arg是這個函式的唯一乙個引數.表明傳遞給start_routine的引數. pthread_exit函式和exit函式類似用來退出執行緒.這個函式結束執行緒,釋放函式的資源,並在最後阻塞,直到其他執行緒使用pthread_join函式等待它.然後將*retval的值傳遞給**thread_return.由於這個函式釋放所以的函式資源,所以retval不能夠指向函式的區域性變數. pthread_join和wait呼叫一樣用來等待指定的執行緒. 下面我們使用乙個例項來解釋一下使用方法.在實踐中,我們經常要備份一些檔案.下面這個程式可以實現當前目錄下的所有檔案備份.備份後的字尾名為bak
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define buffer 512
struct copy_file ;
void *copy(void *arg) }
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)
/* 給執行緒分配空間,其實沒有必要這麼多的 */
if(((thread=(pthread_t *)malloc(sizeof(pthread_t)*num))==null)||
((file=(struct copy_file *)malloc(sizeof(struct copy_file)*num))==null))
for(i=0,j=0;i
/* 我們忽略目錄 */
if(!s_isreg(filestat.st_mode))continue;
if((file[j].infile=open(filename,o_rdonly))<0)
strcat(filename,".bak");
if((file[j].outfile=open(filename,o_wronly|o_creat,s_irusr|s_iwusr))<0)
/* 建立執行緒,進行檔案拷貝 */
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 }
printf("total copy bytes %d/n/a",byte_copy);
free(thread);
free(file);
exit(0);
} 執行緒的介紹就到這裡了,關於執行緒的其他資料可以檢視下面這寫鏈結.
getting started with posix threads
the linuxthreads library
Linux下的C語言程式設計 執行緒程式設計基本操作
第一步建立執行緒 int pthread create pthread t restict tidp,const pthread attr t restict,void start rtn void void restrict arg 第乙個引數 pthread t restict tidp 要建立...
linux下C語言多執行緒程式設計
include include include include define max 10pthread t thread 2 pthread mutex t mut int number 0 i void thread1 printf thread1 主函式在等我完成任務嗎?n pthread e...
多執行緒程式設計 c語言linux下
適用與linux系統 1.了解基本概念 程序 是計算機所執行的乙個任務的描述,是面向作業系統的最小單位,作業系統能執行很多程序 執行自己寫的乙份 程式,就是讓作業系統執行乙個自己程式的程序 作業系統會根據程式分配定量的資源 執行緒 面想程式 程序 的,把乙個程式分成多個執行緒可以實現並髮式,多工執行...