多线程编程指南

线程库

下面简要论述了特定任务及其相关手册页。

创建缺省线程

如果未指定属性对象,则该对象为 NULL,系统会创建具有以下属性的缺省线程:

还可以用 pthread_attr_init() 创建缺省属性对象,然后使用该属性对象来创建缺省线程。有关详细信息,请参见初始化属性一节。

pthread_create 语法

使用 pthread_create(3C) 可以向当前进程中添加新的受控线程。

int	pthread_create(pthread_t *tid, const pthread_attr_t *tattr,

    void*(*start_routine)(void *), void *arg);
#include <pthread.h>



pthread_attr_t() tattr;

pthread_t tid;

extern void *start_routine(void *arg);

void *arg;

int ret; 



/* default behavior*/

ret = pthread_create(&tid, NULL, start_routine, arg);



/* initialized with default attributes */

ret = pthread_attr_init(&tattr);

/* default behavior specified*/

ret = pthread_create(&tid, &tattr, start_routine, arg);

使用具有必要状态行为的 attr 调用 pthread_create() 函数。 start_routine 是新线程最先执行的函数。当 start_routine 返回时,该线程将退出,其退出状态设置为由 start_routine 返回的值。请参见pthread_create 语法

pthread_create() 成功时,所创建线程的 ID 被存储在由 tid 指向的位置中。

使用 NULL 属性参数或缺省属性调用 pthread_create() 时,pthread_create() 会创建一个缺省线程。在对 tattr 进行初始化之后,该线程将获得缺省行为。

pthread_create 返回值

pthread_create() 在调用成功完成之后返回零。其他任何返回值都表示出现了错误。如果检测到以下任一情况,pthread_create() 将失败并返回相应的值。


EAGAIN

描述:

超出了系统限制,如创建的线程太多。


EINVAL

描述:

tattr 的值无效。

等待线程终止

pthread_join() 函数会一直阻塞调用线程,直到指定的线程终止。

pthread_join 语法

使用 pthread_join(3C) 等待线程终止。

int	pthread_join(thread_t tid, void **status);
#include <pthread.h>



pthread_t tid;

int ret;

void *status;



/* waiting to join thread "tid" with status */

ret = pthread_join(tid, &status);



/* waiting to join thread "tid" without status */

ret = pthread_join(tid, NULL); 

指定的线程必须位于当前的进程中,而且不得是分离线程。有关线程分离的信息,请参见设置分离状态

status 不是 NULL 时,status 指向某个位置,在 pthread_join() 成功返回时,将该位置设置为已终止线程的退出状态。

如果多个线程等待同一个线程终止,则所有等待线程将一直等到目标线程终止。然后,一个等待线程成功返回。其余的等待线程将失败并返回 ESRCH 错误。

pthread_join() 返回之后,应用程序可回收与已终止线程关联的任何数据存储空间。

pthread_join 返回值

调用成功完成后,pthread_join() 将返回零。其他任何返回值都表示出现了错误。如果检测到以下任一情况,pthread_join() 将失败并返回相应的值。


ESRCH

描述:

没有找到与给定的线程 ID 相对应的线程。


EDEADLK

描述:

将出现死锁,如一个线程等待其本身,或者线程 A 和线程 B 互相等待。


EINVAL

描述:

与给定的线程 ID 相对应的线程是分离线程。

pthread_join() 仅适用于非分离的目标线程。如果没有必要等待特定线程终止之后才进行其他处理,则应当将该线程分离。

简单线程的示例

示例 2–1 中,一个线程执行位于顶部的过程,该过程首先创建一个辅助线程来执行 fetch() 过程。fetch() 执行复杂的数据库查找操作,查找过程需要花费一些时间。

主线程将等待查找结果,但同时还执行其他操作。因此,主线程将执行其他活动,然后通过执行 pthread_join() 等待辅助线程。

将新线程的 pbe 参数作为栈参数进行传递。这个线程参数之所以能够作为栈参数传递,是因为主线程会等待辅助线程终止。不过,首选方法是使用 malloc 从堆分配存储,而不是传递指向线程栈存储的地址。如果将该参数作为地址传递到线程栈存储,则该地址可能无效或者在线程终止时会被重新分配。


示例 2–1 简单线程程序

void mainline (...)

{

        struct phonebookentry *pbe;

        pthread_attr_t tattr;

        pthread_t helper;

        void *status;



        pthread_create(&helper, NULL, fetch, &pbe);



            /* do something else for a while */



        pthread_join(helper, &status);

        /* it's now safe to use result */

}



void *fetch(struct phonebookentry *arg)

{

        struct phonebookentry *npbe;

        /* fetch value from a database */



        npbe = search (prog_name)

            if (npbe != NULL)

                *arg = *npbe;

        pthread_exit(0);

}   



struct phonebookentry {

        char name[64];

        char phonenumber[32];

        char flags[16];

}

分离线程

pthread_detach(3C)pthread_join(3C) 的替代函数,可回收创建时 detachstate 属性设置为 PTHREAD_CREATE_JOINABLE 的线程的存储空间。

pthread_detach 语法

int	pthread_detach(thread_t tid);
#include <pthread.h>



pthread_t tid;

int ret;



/* detach thread tid */

ret = pthread_detach(tid); 

pthread_detach() 函数用于指示应用程序在线程 tid 终止时回收其存储空间。如果 tid 尚未终止,pthread_detach() 不会终止该线程。

pthread_detach 返回值

pthread_detach() 在调用成功完成之后返回零。其他任何返回值都表示出现了错误。如果检测到以下任一情况,pthread_detach() 将失败并返回相应的值。


EINVAL

描述:

tid 是分离线程。


ESRCH

描述:

tid 不是当前进程中有效的未分离的线程。

为线程特定数据创建键

单线程 C 程序有两类基本数据:局部数据和全局数据。对于多线程 C 程序,添加了第三类数据:线程特定数据。线程特定数据与全局数据非常相似,区别在于前者为线程专有。

线程特定数据基于每线程进行维护。TSD(特定于线程的数据)是定义和引用线程专用数据的唯一方法。每个线程特定数据项都与一个作用于进程内所有线程的键关联。通过使用 key,线程可以访问基于每线程进行维护的指针 (void *)。

pthread_key_create 语法

int	pthread_key_create(pthread_key_t *key,

    void (*destructor) (void *));
#include <pthread.h>



pthread_key_t key;

int ret;



/* key create without destructor */

ret = pthread_key_create(&key, NULL);



/* key create with destructor */

ret = pthread_key_create(&key, destructor); 

可以使用 pthread_key_create(3C) 分配用于标识进程中线程特定数据的。键对进程中的所有线程来说是全局的。创建线程特定数据时,所有线程最初都具有与该键关联的 NULL 值。

使用各个键之前,会针对其调用一次 pthread_key_create()。不存在对键(为进程中所有的线程所共享)的隐含同步。

创建键之后,每个线程都会将一个值绑定到该键。这些值特定于线程并且针对每个线程单独维护。如果创建该键时指定了 destructor 函数,则该线程终止时,系统会解除针对每线程的绑定。

pthread_key_create() 成功返回时,会将已分配的键存储在 key 指向的位置中。调用方必须确保对该键的存储和访问进行正确的同步。

使用可选的析构函数 destructor 可以释放过时的存储。如果某个键具有非 NULL destructor 函数,而线程具有一个与该键关联的非 NULL 值,则该线程退出时,系统将使用当前的相关值调用 destructor 函数。destructor 函数的调用顺序不确定。

pthread_key_create 返回值

pthread_key_create() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,pthread_key_create() 将失败并返回相应的值。


EAGAIN

描述:

key 名称空间已经用完。


ENOMEM

描述:

此进程中虚拟内存不足,无法创建新键。

删除线程特定数据键

使用 pthread_key_delete(3C) 可以销毁现有线程特定数据键。由于键已经无效,因此将释放与该键关联的所有内存。引用无效键将返回错误。Solaris 线程中没有类似的函数。

pthread_key_delete 语法

int	pthread_key_delete(pthread_key_t key);
#include <pthread.h>



pthread_key_t key;

int ret;



/* key previously created */

ret = pthread_key_delete(key); 

如果已删除,则使用调用 pthread_setspecific()pthread_getspecific() 引用该键时,生成的结果将是不确定的。

程序员在调用删除函数之前必须释放所有线程特定资源。删除函数不会调用任何析构函数。反复调用 pthread_key_create()pthread_key_delete() 可能会产生问题。如果 pthread_key_delete() 将键标记为无效,而之后 key 的值不再被重用,那么反复调用它们就会出现问题。对于每个所需的键,应当只调用 pthread_key_create() 一次。

pthread_key_delete 返回值

pthread_key_delete() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_key_delete() 将失败并返回相应的值。


EINVAL

描述:

key 的值无效。

设置线程特定数据

使用 pthread_setspecific(3C) 可以为指定线程特定数据键设置线程特定绑定。

pthread_setspecific 语法

int	pthread_setspecific(pthread_key_t key, const void *value);
#include <pthread.h>



pthread_key_t key;

void *value;

int ret;



/* key previously created */

ret = pthread_setspecific(key, value); 

pthread_setspecific 返回值

pthread_setspecific() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,pthread_setspecific() 将失败并返回相应的值。


ENOMEM

描述:

虚拟内存不足。


EINVAL

描述:

key 无效。


注 –

设置新绑定时,pthread_setspecific() 不会释放其存储空间。必须释放现有绑定,否则会出现内存泄漏。


获取线程特定数据

请使用 pthread_getspecific(3C) 获取调用线程的绑定,并将该绑定存储在 value 指向的位置中。

pthread_getspecific 语法

void	*pthread_getspecific(pthread_key_t key);
#include <pthread.h>



pthread_key_t key;

void *value;



/* key previously created */

value = pthread_getspecific(key); 

pthread_getspecific 返回值

pthread_getspecific 不返回任何错误。

全局和专用线程特定数据的示例

示例 2–2 显示的代码是从多线程程序中摘录出来的。这段代码可以由任意数量的线程执行,但该代码引用了两个全局变量:errnomywindow。这些全局值实际上应当是对每个线程专用项的引用。


示例 2–2 线程特定数据-全局但专用

body() {

    ...



    while (write(fd, buffer, size) == -1) {

        if (errno != EINTR) {

            fprintf(mywindow, "%s\n", strerror(errno));

            exit(1);

        }

    }



    ...



}

errno 引用应该从线程所调用的例程获取系统错误,而从其他线程所调用的例程获取系统错误。因此,线程不同,引用 errno 所指向的存储位置也不同。

mywindow 变量指向一个 stdio (标准 IO)流,作为线程专属的流窗口。因此,与 errno 一样,线程不同,引用 mywindow 所指向的存储位置也不同。最终,这个引用指向不同的流窗口。唯一的区别在于系统负责处理 errno,而程序员必须处理对 mywindow 的引用。

下一个示例说明对 mywindow 的引用如何工作。预处理程序会将对 mywindow 的引用转换为对 _mywindow() 过程的调用。

此例程随后调用 pthread_getspecific()pthread_getspecific() 接收 mywindow_key 全局变量作为输入参数,以输出参数 win 返回该线程的窗口。


示例 2–3 将全局引用转化为专用引用

thread_key_t mywin_key;



FILE *_mywindow(void) {

    FILE *win;



    win = pthread_getspecific(mywin_key);

    return(win);

}



#define mywindow _mywindow()



void routine_uses_win( FILE *win) {

    ...

}



void thread_start(...) {

    ...

    make_mywin();

    ...

    routine_uses_win( mywindow )

    ...

}

mywin_key 变量标识一类变量,对于该类变量,每个线程都有其各自的专用副本。这些变量是线程特定数据。每个线程都调用 make_mywin() 以初始化其时限并安排其 mywindow 实例以引用线程特定数据。

调用此例程之后,此线程可以安全地引用 mywindow,调用 _mywindow() 之后,此线程将获得对其专用时限的引用。引用 mywindow 类似于直接引用线程专用数据。

示例 2–4 说明如何设置引用。


示例 2–4 初始化线程特定数据

void make_mywindow(void) {

    FILE **win;

    static pthread_once_t mykeycreated = PTHREAD_ONCE_INIT;



    pthread_once(&mykeycreated, mykeycreate);



    win = malloc(sizeof(*win));

    create_window(win, ...);



    pthread_setspecific(mywindow_key, win);

}



void mykeycreate(void) {

    pthread_key_create(&mywindow_key, free_key);

}



void free_key(void *win) {

    free(win);

}

首先,得到一个唯一的键值,mywin_key。此键用于标识线程特定数据类。第一个调用 make_mywin() 的线程最终会调用 pthread_key_create(),该函数将唯一的 key 赋给其第一个参数。第二个参数是 destructor 函数,用于在线程终止后将该线程的特定于该线程的数据项实例解除分配。

接下来为调用方的线程特定数据项的实例分配存储空间。获取已分配的存储空间,调用 create_window(),以便为该线程设置时限。win 指向为该时限分配的存储空间。最后,调用 pthread_setspecific(),将 win 与该键关联。

以后,每当线程调用 pthread_getspecific() 以传递全局 key,线程都会获得它在前一次调用 pthread_setspecific() 时设置的与该键关联的值)。

线程终止时,会调用在 pthread_key_create() 中设置的 destructor 函数。每个 destructor 函数仅在终止线程通过调用 pthread_setspecific()key 赋值之后才会被调用。

获取线程标识符

请使用 pthread_self(3C) 获取调用线程的 thread identifier

pthread_self 语法

pthread_t	 pthread_self(void);
#include <pthread.h>



pthread_t tid;



tid = pthread_self();

pthread_self 返回值

pthread_self() 返回调用线程的 thread identifier

比较线程 ID

请使用 pthread_equal(3C) 对两个线程的线程标识号进行比较。

pthread_equal 语法

int	 pthread_equal(pthread_t tid1, pthread_t tid2);
#include <pthread.h>



pthread_t tid1, tid2;

int ret;



ret = pthread_equal(tid1, tid2);

pthread_equal 返回值

如果 tid1tid2 相等,pthread_equal() 将返回非零值,否则将返回。如果 tid1tid2 是无效的线程标识号,则结果无法预测。

初始化线程

使用 pthread_once(3C),可以在首次调用 pthread_once 时调用初始化例程。以后调用 pthread_once() 将不起作用。

pthread_once 语法

int	 pthread_once(pthread_once_t *once_control,

    void (*init_routine)(void));
#include <pthread.h>



pthread_once_t once_control = PTHREAD_ONCE_INIT;

int ret;



ret = pthread_once(&once_control, init_routine);

once_control 参数用来确定是否已调用相关的初始化例程。

pthread_once 返回值

pthread_once() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_once() 将失败并返回相应的值。


EINVAL

描述:

once_controlinit_routineNULL

停止执行线程

使用 sched_yield(3RT),可以使当前线程停止执行,以便执行另一个具有相同或更高优先级的线程。

sched_yield 语法

int	 sched_yield(void);
#include <sched.h>



int ret;



ret = sched_yield();

sched_yield 返回值

sched_yield() 在成功完成之后返回零。否则,返回 -1,并设置 errno 以指示错误状态。


ENOSYS

描述:

本实现不支持 sched_yield

设置线程的优先级

请使用 pthread_setschedparam(3C) 修改现有线程的优先级。此函数对于调度策略不起作用。

pthread_setschedparam 语法

int	 pthread_setschedparam(pthread_t tid, int policy,

    const struct sched_param *param);
#include <pthread.h>



pthread_t tid;

int ret;

struct sched_param param;

int priority;



/* sched_priority will be the priority of the thread */

sched_param.sched_priority = priority;

policy = SCHED_OTHER;



/* scheduling parameters of target thread */

ret = pthread_setschedparam(tid, policy, &param); 

pthread_setschedparam 返回值

pthread_setschedparam() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,pthread_setschedparam() 函数将失败并返回相应的值。


EINVAL

描述:

所设置属性的值无效。


ENOTSUP

描述:

尝试将该属性设置为不受支持的值。

获取线程的优先级

pthread_getschedparam(3C) 可用来获取现有线程的优先级。

pthread_getschedparam 语法

int	 pthread_getschedparam(pthread_t tid, int policy,

    struct schedparam *param);
#include <pthread.h>



pthread_t tid;

sched_param param;

int priority;

int policy;

int ret;



/* scheduling parameters of target thread */

ret = pthread_getschedparam (tid, &policy, &param);



/* sched_priority contains the priority of the thread */

priority = param.sched_priority; 

pthread_getschedparam 返回值

pthread_getschedparam() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,该函数将失败并返回对应的值。


ESRCH

描述:

tid 指定的值不引用现有的线程。

向线程发送信号

请使用 pthread_kill(3C) 向线程发送信号。

pthread_kill 语法

int	 pthread_kill(thread_t tid, int sig);
#include <pthread.h>

#include <signal.h>



int sig;

pthread_t tid;

int ret;



ret = pthread_kill(tid, sig);

pthread_kill() 将信号 sig 发送到由 tid 指定的线程。tid 所指定的线程必须与调用线程在同一个进程中。sig 参数必须来自 signal(5) 提供的列表。

如果 sig 为零,将执行错误检查,但并不实际发送信号。此错误检查可用来检查 tid 的有效性。

pthread_kill 返回值

pthread_kill() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下任一情况,pthread_kill() 将失败并返回相应的值。


EINVAL

描述:

sig 是无效的信号量。


ESRCH

描述:

当前的进程中找不到 tid

访问调用线程的信号掩码

请使用 pthread_sigmask(3C) 更改或检查调用线程的信号掩码。

pthread_sigmask 语法

int	pthread_sigmask(int how, const sigset_t *new, sigset_t *old);
#include <pthread.h>

#include <signal.h>



int ret;

sigset_t old, new;



ret = pthread_sigmask(SIG_SETMASK, &new, &old); /* set new mask */

ret = pthread_sigmask(SIG_BLOCK, &new, &old); /* blocking mask */

ret = pthread_sigmask(SIG_UNBLOCK, &new, &old); /* unblocking */

how 用来确定如何更改信号组。how 可以为以下值之一:

new 的值为 NULL 时,how 的值没有意义,线程的信号掩码不发生变化。要查询当前已阻塞的信号,请将 NULL 值赋给 new 参数。

除非 old 变量为 NULL,否则 old 指向用来存储以前的信号掩码的空间。

pthread_sigmask 返回值

pthread_sigmask() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_sigmask() 将失败并返回相应的值。


EINVAL

描述:

未定义 how 的值。

安全地 Fork

请参见解决方案: pthread_atfork中有关 pthread_atfork(3C) 的论述。

pthread_atfork 语法

int pthread_atfork(void (*prepare) (void), void (*parent) (void),

    void (*child) (void) );

pthread_atfork 返回值

pthread_atfork() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_atfork() 将失败并返回相应的值。


ENOMEM

描述:

表空间不足,无法记录 Fork 处理程序地址。

终止线程

请使用 pthread_exit(3C) 终止线程。

pthread_exit 语法

void	 pthread_exit(void *status);
#include <pthread.h>



void *status;



pthread_exit(status); /* exit with status */

pthread_exit() 函数可用来终止调用线程。将释放所有线程特定数据绑定。如果调用线程尚未分离,则线程 ID 和 status 指定的退出状态将保持不变,直到应用程序调用 pthread_join() 以等待该线程。否则,将忽略 status。线程 ID 可以立即回收。有关线程分离的信息,请参见设置分离状态

pthread_exit 返回值

调用线程将终止,退出状态设置为 status 的内容。

结束

线程可通过以下方法来终止执行:

线程的缺省行为是拖延,直到其他线程通过 "joining" 拖延线程确认其已死亡。此行为与非分离的缺省 pthread_create() 属性相同,请参见 pthread_detach。join 的结果是 joining 线程得到已终止线程的退出状态,已终止的线程将消失。

有一个重要的特殊情况,即当初始线程(即调用 main() 的线程)从 main() 调用返回时或调用 exit() 时,整个进程及其所有的线程将终止。因此,一定要确保初始线程不会从 main() 过早地返回。

请注意,如果主线程仅仅调用了 pthread_exit,则仅主线程本身终止。进程及进程内的其他线程将继续存在。所有线程都已终止时,进程也将终止。

取消线程

取消操作允许线程请求终止其所在进程中的任何其他线程。不希望或不需要对一组相关的线程执行进一步操作时,可以选择执行取消操作。

取消线程的一个示例是异步生成取消条件,例如,用户请求关闭或退出正在运行的应用程序。另一个示例是完成由许多线程执行的任务。其中的某个线程可能最终完成了该任务,而其他线程还在继续运行。由于正在运行的线程此时没有任何用处,因此应当取消这些线程。

取消点

仅当取消操作安全时才应取消线程。pthreads 标准指定了几个取消点,其中包括:

缺省情况下将启用取消功能。有时,您可能希望应用程序禁用取消功能。如果禁用取消功能,则会导致延迟所有的取消请求,直到再次启用取消请求。

有关禁用取消功能的信息,请参见pthread_setcancelstate 语法

放置取消点

执行取消操作存在一定的危险。大多数危险都与完全恢复不变量和释放共享资源有关。取消线程时一定要格外小心,否则可能会使互斥保留为锁定状态,从而导致死锁。或者,已取消的线程可能保留已分配的内存区域,但是系统无法识别这一部分内存,从而无法释放它。

标准 C 库指定了一个取消接口用于以编程方式允许或禁止取消功能。该库定义的取消点是一组可能会执行取消操作的点。该库还允许定义取消处理程序的范围,以确保这些处理程序在预期的时间和位置运行。取消处理程序提供的清理服务可以将资源和状态恢复到与起点一致的状态。

必须对应用程序有一定的了解,才能放置取消点并执行取消处理程序。互斥肯定不是取消点,只应当在必要时使之保留尽可能短的时间。

请将异步取消区域限制在没有外部依赖性的序列,因为外部依赖性可能会产生挂起的资源或未解决的状态条件。在从某个备用的嵌套取消状态返回时,一定要小心地恢复取消状态。该接口提供便于进行恢复的功能:pthread_setcancelstate(3C) 在所引用的变量中保留当前的取消状态,pthread_setcanceltype(3C) 以同样的方式保留当前的取消类型。

在以下三种不同的情况下可能会执行取消操作:

缺省情况下,仅在 POSIX 标准可靠定义的点执行取消操作。

无论何时,都应注意资源和状态恢已复到与起点一致的状态。

取消线程

请使用 pthread_cancel(3C) 取消线程。

pthread_cancel 语法

int	pthread_cancel(pthread_t thread);
#include <pthread.h>



pthread_t thread;

int ret;



ret = pthread_cancel(thread);

取消请求的处理方式取决于目标线程的状态。状态由以下两个函数确定:pthread_setcancelstate(3C)pthread_setcanceltype(3C)

pthread_cancel 返回值

pthread_cancel() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,该函数将失败并返回对应的值。


ESRCH

描述:

没有找到与给定线程 ID 相对应的线程。

启用或禁用取消功能

请使用 pthread_setcancelstate(3C) 启用或禁用线程取消功能。创建线程时,缺省情况下线程取消功能处于启用状态。

pthread_setcancelstate 语法

int	pthread_setcancelstate(int state, int *oldstate);
#include <pthread.h>



int oldstate;

int ret;



/* enabled */

ret = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &oldstate);



/* disabled */

ret = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &oldstate);

pthread_setcancelstate 返回值

pthread_setcancelstate() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,pthread_setcancelstate() 函数将失败并返回相应的值。


EINVAL

描述:

状态不是 PTHREAD_CANCEL_ENABLEPTHREAD_CANCEL_DISABLE

设置取消类型

使用 pthread_setcanceltype(3C) 可以将取消类型设置为延迟或异步模式。

pthread_setcanceltype 语法

int	pthread_setcanceltype(int type, int *oldtype);
#include <pthread.h>



int oldtype;

int ret;



/* deferred mode */

ret = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &oldtype);



/* async mode*/

ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype);

创建线程时,缺省情况下会将取消类型设置为延迟模式。在延迟模式下,只能在取消点取消线程。在异步模式下,可以在执行过程中的任意一点取消线程。因此建议不使用异步模式。

pthread_setcanceltype 返回值

pthread_setcanceltype() 在成功完成之后返回零。其他任何返回值都表示出现了错误。如果出现以下情况,该函数将失败并返回对应的值。


EINVAL

描述:

类型不是 PTHREAD_CANCEL_DEFERREDPTHREAD_CANCEL_ASYNCHRONOUS

创建取消点

请使用 pthread_testcancel(3C) 为线程建立取消点。

pthread_testcancel 语法

void pthread_testcancel(void);
#include <pthread.h>



pthread_testcancel(); 

当线程取消功能处于启用状态且取消类型设置为延迟模式时,pthread_testcancel() 函数有效。如果在取消功能处于禁用状态下调用 pthread_testcancel(),则该函数不起作用。

请务必仅在线程取消操作安全的序列中插入 pthread_testcancel()。除通过 pthread_testcancel() 调用以编程方式建立的取消点以外,pthread 标准还指定了几个取消点。有关更多详细信息,请参见取消点

pthread_testcancel 返回值

pthread_testcancel() 没有返回值。

将处理程序推送到栈上

使用清理处理程序,可以将状态恢复到与起点一致的状态,其中包括清理已分配的资源和恢复不变量。使用 pthread_cleanup_push(3C)pthread_cleanup_pop(3C) 函数可以管理清理处理程序。

在程序的同一词法域中可以推送和弹出清理处理程序。推送和弹出操作应当始终匹配,否则会生成编译器错误。

pthread_cleanup_push 语法

请使用 pthread_cleanup_push(3C) 将清理处理程序推送到清理栈 (LIFO)。

void pthread_cleanup_push(void(*routine)(void *), void *args);
#include <pthread.h>



/* push the handler "routine" on cleanup stack */

pthread_cleanup_push (routine, arg); 

pthread_cleanup_push 返回值

pthread_cleanup_push() 没有返回值。

从栈中弹出处理程序

请使用 pthread_cleanup_pop(3C) 从清理栈中弹出清理处理程序。

pthread_cleanup_pop 语法

void pthread_cleanup_pop(int execute);
#include <pthread.h>



/* pop the "func" out of cleanup stack and execute "func" */

pthread_cleanup_pop (1);



/* pop the "func" and DONT execute "func" */

pthread_cleanup_pop (0); 

如果弹出函数中的参数为非零值,则会从栈中删除该处理程序并执行该处理程序。如果该参数为零,则会弹出该处理程序,而不执行它。

线程显式或隐式调用 pthread_exit(3C) 时,或线程接受取消请求时,会使用非零参数有效地调用 pthread_cleanup_pop()

pthread_cleanup_pop 返回值

pthread_cleanup_pop() 没有返回值。