1. 程式人生 > 實用技巧 >Linux使用者態執行緒pthread簡單應用

Linux使用者態執行緒pthread簡單應用

1、pthread_exit函式

void pthread_exit( void * value_ptr );
執行緒的終止可以是呼叫pthread_exit手動結束或者該執行緒的例程執行完成自動結束。
也就是說,一個執行緒可以隱式的退出,也可以顯式的呼叫pthread_exit函式來退出。 pthread_exit函式唯一的引數value_ptr是函式的返回程式碼,只要pthread_join中的第二個引數value_ptr不是NULL,這個值將被傳遞給value_ptr。
使用函式pthread_exit退出執行緒,這是執行緒的主動行為;
由於一個程序中的多個執行緒是共享資料段的,因此通常線上程退出之後,退出執行緒所佔用的資源並不會隨著執行緒的終止而得到釋放,
但是可以用pthread_join()函式來同步並釋放資源。

retval:pthread_exit()呼叫執行緒的返回值,可由其他函式如pthread_join來檢索獲取。

2、pthread_join函式

int pthread_join( pthread_t thread, void * * value_ptr ); 函式pthread_join的作用是,等待一個執行緒終止。 
呼叫pthread_join的執行緒,將被掛起,直到引數thread所代表的執行緒終止時為止。
pthread_join是一個執行緒阻塞函式,呼叫它的函式將一直等到被等待的執行緒結束為止。 如果value_ptr不為NULL,那麼執行緒thread的返回值儲存在該指標指向的位置。
該返回值可以是由pthread_exit給出的值,或者該執行緒被取消而返回PTHREAD_CANCELED。
3、pthread_exit函式在main函式中的用法





例子:
/*thread.c*/
#include <stdio.h>
#include <pthread.h>
 
/*執行緒一*/
void thread_1(void)
{
    int i=0;
    for(i=0;i<=1000;i++)
    {
        printf("This is a pthread1.\n");
        if(i==500)
            pthread_exit(0);//用pthread_exit()來呼叫執行緒的返回值,用來退出執行緒,但是退出執行緒所佔用的資源不會隨著執行緒的終止而得到釋放
sleep(1); } } /*執行緒二*/ void thread_2(void) { int i; for(i=0;i<300;i++) printf("This is a pthread2.\n"); pthread_exit(0);//用pthread_exit()來呼叫執行緒的返回值,用來退出執行緒,但是退出執行緒所佔用的資源不會隨著執行緒的終止而得到釋放 } int main(void) { pthread_t id_1,id_2; int i,ret; /*建立執行緒一*/ ret=pthread_create(&id_1,NULL,(void *) thread_1,NULL); if(ret!=0) { printf("Create pthread1 error!\n"); return -1; } /*建立執行緒二*/ ret=pthread_create(&id_2,NULL,(void *) thread_2,NULL); if(ret!=0) { printf("Create pthread2 error!\n"); return -1; } /*等待執行緒結束*/ pthread_join(id_1,NULL); pthread_join(id_2,NULL); return 0; }

備註:pthread庫不是Linux系統預設的庫,連線時需要使用靜態庫libpthread.a,所以線上程函式在編譯時,需要連線庫函式。
makefile新增:gcc create.c -o pthreadapp -lpthread


參考引用:
https://blog.csdn.net/youbang321/article/details/7816016#