pthread_exit

執行緒通過調用pthread_exit函式終止執行,就如同進程在結束時調用exit函式一樣。這個函式的作用是,終止調用它的執行緒並返回一個指向某個對象的指針。

定義

void pthread_exit(void* retval);

pthread_exit()

參數

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

void *print_message_function( void *ptr )

{

char *message;

message = (char *) ptr;

printf("%s \t", message);

printf("PID: %ld \n", pthread_self());

pthread_exit ("thread all done"); // 重點看 pthread_exit() 的參數,是一個字串,這個參數的指針可以通過

// pthread_join( thread1, &pth_join_ret1);

}

main()

{

pthread_t thread1, thread2;

char *message1 = "Thread 1";

char *message2 = "Thread 2";

int iret1, iret2;

void *pth_join_ret1;//="thread1 has done!";

void *pth_join_ret2;//="thread2 has done!";

/* Create independant threads each of which will execute function */

//pthread_create return 0 if create a thread is ok!

iret1 = pthread_create( &thread1, NULL, print_message_function, (void*)"thread one_here");

iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);

pthread_join( thread1, &pth_join_ret1);

pthread_join( thread2, &pth_join_ret2);

//

//if(pth_join_ret1==NULL || pth_join_ret2==NULL)

//{

// printf("in %d lines \n",__LINE__);

//}

printf("Thread 1 returns: %d\n",iret1);

printf("Thread 2 returns: %d\n",iret2);

printf("pthread_join 1 returns: %s\n",(char *)pth_join_ret1);

printf("pthread_join 2 returns: %s\n",(char *)pth_join_ret2);//目的就是列印 執行緒退出時的返回值

exit(0);

}

//重點看上面紅色注釋。以前確實沒注意,今天幫一個新同事調試程式才仔細看了說明

DESCRIPTION

pthread_exit terminates the execution of the calling

thread. All cleanup handlers that have been set for the

calling thread with pthread_cleanup_push(3) are executed

in reverse order (the most recently pushed handler is exe-

cuted first). Finalization functions for thread-specific

data are then called for all keys that have non- NULL val-

ues associated with them in the calling thread (see

pthread_key_create(3)). Finally, execution of the calling

thread is stopped.

The retval argument is the return value of the thread. It

can be consulted from another thread using

pthread_join(3).

相關詞條

熱門詞條

聯絡我們