天天看点

POSIX创建终止线程创建线程终止线程线程范例

本文参考《嵌入式Linux开发教程》和《Linux/UNIX系统编程手册》。

创建线程

thread 用来指向新创建线程的 ID;

attr 用来表示一个封装了线程各种属性的属性对象,如果 attr 为 NULL,新线程就使用默认的属性;

start_routine 是线程开始执行的时候调用的函数的名字;

arg 为参数 start_routine 指定函数的参数。

终止线程

进程的终止可以通过直接调用 exit()、执行 main()中的 return、或者通过进程的某个其它线程调用 exit()来实现。在以上任何一种情况发生时,所有的线程都会被终止。如果主线程在创建了其它线程后没有任务需要处理,那么它应该阻塞等待直到所有线程都结束为止,或者应该调用 pthread_exit(NULL)。

调用 exit()函数会使整个进程终止,而调用 pthread_exit()只会使得调用线程终止,同时在创建的线程的顶层执行 return 线程会隐式地调用 pthread_exit()。

retval 是一个 void 类型的指针,可以将线程的返回值当作 pthread_exit()的参数传入,这个值同样被 pthread_join()当作退出状态处理。如果进程的最后一个线程调用了 pthread_exit(),进程会带着状态返回值 0 退出。

线程范例

主线程创建了 5 个线程,这 5 个线程和主线程并发执行,主线程创建完线程后调用 pthread_exit()函数退出线程,其它线程分别

打印当前线程的序号。当主线程先于其它进程执行 pthread_exit()时,进程还不会退出,只有最后一个线程也完成了,进程才会退出。

[email protected]-virtual-machine:~/workspace/test$ cat sample.c 
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid){	//线程函数
   long tid;
   tid = (long)threadid;
   printf("Hello World! It's me, thread #%ld!\n", tid);	//打印线程对应的参数
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){	//循环创建5个线程
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);	//创建线程
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }
   printf("In main: exit!\n");
   pthread_exit(NULL);	//主线程退出
}

           

下面为运行结果,程序中主线程调用了 pthread_exit()函数并不会将整个进程终止,而是当最后一个线程调用 pthread_exit()时程序才完成运行。

[email protected]-virtual-machine:~/workspace/test$ gcc sample.c -o sample -[email protected]-virtual-machine:~/workspace/test$ ./sample
In main: creating thread 0
In main: creating thread 1
Hello World! It's me, thread #0!
Hello World! It's me, thread #1!
In main: creating thread 2
In main: creating thread 3
Hello World! It's me, thread #2!
In main: creating thread 4
Hello World! It's me, thread #3!
In main: exit!
Hello World! It's me, thread #4!
[email protected]-virtual-machine:~/workspace/test$ 
           

继续阅读