一 Linux--多線程( 四 )

運行結果小伙伴們自己運行一下吧 。
示例2:pthread_exit函數
void pthread_exit(void *retval);功能: 退出調用線程 。一個進程中的多個線程是共享該進程的數據段,因此,通常線程退出后所占用的資源并不會釋放 。參數:    retval:存儲線程退出狀態的指針 。返回值:無#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){  int count = 0;  while (1){    printf(" new threaad is running, pid is %d, thread id is %p\n", getpid(), pthread_self());    sleep(1);    if (++count == 3){      pthread_exit(NULL);    }  }}int main(){  pthread_t thread;  pthread_create(&thread, NULL, pthreadrun, NULL);  while (1){    printf("main thread is running, pid is %d, thread id is %p\n", getpid(), pthread_self());    sleep(1);  }  return 0;}在線程調度函數中pthread_exit(NULL)等價于return。
示例3:pthread_cancel函數
 int pthread_cancel(pthread_t thread);功能: 殺死(取消)線程參數: thread:目標線程ID返回值: 成功:0 失敗:出錯編號注意:線程的取消不是實時的,而是有一定的延時 。需要等待線程到達某個取消點(檢查點) 。
#include <stdio.h>#include <pthread.h>#include <unistd.h>void* pthreadrun(void* arg){  int count = 0;  while (1){    printf(" new threaad is running, pid is %d, thread id is %p,count is %d\n", getpid(), pthread_self(),count);    sleep(1);  }}int main(){  pthread_t thread;  pthread_create(&thread, NULL, pthreadrun, NULL);  int count = 0;  while (1){    printf("main thread is running, pid is %d, thread id is %p,count is %d\n", getpid(), pthread_self(),count);    sleep(1);    if (++count == 3){      pthread_cancel(thread);      printf("new thread is canceled...\n");    }  }  return 0;}運行結果如下:

一 Linux--多線程

文章插圖
主線程把子線程謀殺了,只能取消同一個進程中的線程,還可以根據count的值看出,每個線程有自己獨立的PCB,在PCB中存在自己的棧區 。
線程等待線程等待的原因:
  • 已經退出的線程,其空間沒有被釋放,仍然在進程的地址空間內 。
  • 創建新的線程不會復用剛才退出線程的地址空間 。
int pthread_join(pthread_t thread, void **retval);功能:    等待線程結束(此函數會阻塞),并回收線程資源,類似于進程的wait()函數 。如果線程已經結束,那么該函數會立刻返回 。參數:    thread:被等待的線程號    retval:用來存儲線程退出狀態的指針的地址返回值:     成功:0     失?。悍?#include <stdio.h>#include <pthread.h>#include <unistd.h>long retval = 10;void* pthreadrun(void* arg){  int count = 0;  while (1){    printf(" new threaad is running, pid is %d, thread id is %p\n", getpid(), pthread_self());    sleep(1);    if (++count == 3){      pthread_exit((void*)retval);    }  }}int main(){  pthread_t thread;  pthread_create(&thread, NULL, pthreadrun, NULL);  printf("main thread is waiting new thread\n");  void* ret = NULL;  pthread_join(thread, &ret);  printf("new thread has exited, exit code is %ld\n", (long)ret);  return 0;}

推薦閱讀