线程终止
如果进程中的任一线程调用了exit,_Exit或者_exit,那么整个进程就会终止。与此类似,如果信号的默认动作是终止进程,那么,把该信号发送到线程会终止整个进程。
单个线程可以通过下列三种方式退出,在不终止整个进程的情况下停止它的控制流。
(1):从启动例程中返回,返回值是线程的退出码
(2):线程可以被同一进程中的其他线程取消
(3):线程调用pthread_exit()
pthread_exit函数:
- 原型: void pthread_exit(void *rval_ptr);
- 头文件: <pthread.h>
- 参数: rval_ptr是一个无类型指针, 指向线程的返回值存储变量.
pthread_join函数:
- 原型: int pthread_join(pthread_t thread, void **rval_ptr);
- 头文件: <pthread.h>
- 返回值: 成功则返回0, 否则返回错误编号.
- 参数:
- thread: 线程ID.
- rval_ptr: 指向返回值的指针(返回值也是个指针).
- 说明:
- 调用线程将一直阻塞, 直到指定的线程调用pthread_exit, 从启动例程返回或被取消.
- 如果线程从它的启动例程返回, rval_ptr包含返回码.
- 如果线程被取消, 由rval_ptr指定的内存单元置为: PTHREAD_CANCELED.
- 如果对返回值不关心, 可把rval_ptr设为NULL.
实例:
#include <pthread.h>
#include <stdio.h>
/* print process and thread IDs */
void printids(const char *s)
{
pid_t pid, ppid;
pthread_t tid;
pid= getpid();
ppid = getppid();
tid = pthread_self();
printf("%16s pid %5u ppid %5u tid %16u (0x%x) ",
s, (unsigned int)pid, (unsigned int)ppid,
(unsigned int)tid, (unsigned int)tid);
}
/* thread process */
void *thread_func(void *arg);
{
printids("new thread: ");
return (void *)108;
}
/* main func */
int main()
{
int err;
void *tret; /* thread return value */
pthread_t ntid;
err = pthread_create(&ntid, NULL, thread_func, NULL);
if (err != 0)
perror("can't create thread");
err = pthread_join(ntid, &tret);
if (err != 0)
perror("can't join thread");
printids("main thread: ");
printf("thread exit code: %d ", (int)tret);
sleep(1);
return 0;
}
这段代码是通过前一个实例改编的, 执行流程如下:
- 首先创建一个新线程, 该线程在打印完IDs后, 返回108.
- 然后用pthread_join获取该线程返回值, 存于tret中.
- 主线程打印IDs.
- 主线程打印tret, 即新线程的返回值.