1. 程式人生 > >筆記8 linux多執行緒程式設計

筆記8 linux多執行緒程式設計

執行緒(thread ) < 程序 執行緒(thread ) -----> 依賴 <pthread.h> 和庫 libpthread.a①建立執行緒int pthread_create(pthread_t * tidp,const pthread_attr_t *attr,void *(* start_rtn)(void),void *arg)tidp:執行緒idattr:執行緒屬性(通常為空NULL)strat_rtn:執行緒要執行的函式arg:strat_rtn的引數進行編譯的時候要加上 -lpthread (因為需要libpthread.a庫)gcc filename -lpthread #include <stdio.h>#include <pthread.h>void *myThread1(void){ int i; for (i=0; i<100; i++) { printf("This is the 1st pthread,created by zieckey.\n"); sleep(1);//Let this thread to sleep 1 second,and then continue to run
}}void *myThread2(void){ int i; for (i=0; i<100; i++) { printf("This is the 2st pthread,created by zieckey.\n"); sleep(1); }}int main(){ int i=0, ret=0; pthread_t id1,id2; /*建立執行緒1*/ ret = pthread_create(&id1, NULL, (void*)myThread1, NULL); if (ret) { printf("Create pthread error!\n");
return 1; } /*建立執行緒2*/ ret = pthread_create(&id2, NULL, (void*)myThread2, NULL); if (ret) { printf("Create pthread error!\n"); return 1; } pthread_join(id1, NULL); pthread_join(id2, NULL); return 0;}②終止執行緒如果程序中任何一個執行緒中呼叫exit 或者 _exit,那麼整個程序都會終止。執行緒退出的方式有:1.執行緒從啟動例程中返回 return 2.執行緒可以被另一個程序終止3.執行緒自己呼叫pthread_exit函式4.非正常終止,(例如:其他執行緒的干預,或者自身執行出錯(如訪問非法地址)而退出)void pthread_exit(void * rval_ptr); rval_ptr:執行緒退出後返回的指標③執行緒等待int pthrad_join(pthread_t tid,void ** rval_ptr)功能:阻塞呼叫執行緒,直到執行緒終止。 ④執行緒標識pthread_t pthread_self(void)功能:獲取呼叫執行緒的 thread identifier 返回:TID⑥執行緒非法終止時,清除佔用空間pthread_cleanup_pushpthread_cleanup_pop在這對函式中間的程式碼,若出現非法終止,那麼會執行pthread_cleanup_push所指定的清理函式,不包括return.
void pthread_cleanup_push(void (*rtn)(void *),void *arg)功能:將清除函式推入清除棧rtn:清除函式 arg:清除函式的引數void pthread_cleanup_pop(int execute)功能:將清除函式彈出清除棧 execute 非0:執行 0:不執行 (執行上面的指定函式)