一 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     失败:非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;}

推荐阅读