一 Linux--多线程( 五 )


示例1:return退出线程调度函数
#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++ == 5){      return (void*)10;    }  }}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;}运行结果小伙伴们自己运行一下吧 。
示例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;}运行结果如下:

经验总结扩展阅读