有"pthread_getcancelstate"这样的函数吗?

Is There a Function Like "pthread_getcancelstate"?

Linux Pthread 库包括 2 个函数来设置线程的取消状态和取消类型:

如何接收这些状态和类型?有没有像pthread_getcancelstate或者pthread_getcanceltype这样的函数?我在网上搜索,没有找到解决方法。

由于函数 pthread_setcancelstate() and pthread_setcanceltype() return 旧状态通过参数列表,您可以调用函数来设置 'safe' state/type (PTHREAD_CANCEL_DISABLEPTHREAD_CANCEL_DEFERRED,我认为),如果旧的 state/type 不一样,则再次调用该函数以恢复旧的 state/type。新 state/type.

似乎没有 'no-op' 值
int pthread_getcancelstate(int *oldstate)
{
    int dont_care;
    int rc = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, oldstate);
    if (rc == 0 && *oldstate != PTHREAD_CANCEL_DISABLE)
        rc = pthread_setcancelstate(*oldstate, &dont_care);
    return rc;
}

int pthread_getcanceltype(int *oldtype)
{
    int dont_care;
    int rc = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, oldtype);
    if (rc == 0 && *oldtype != PTHREAD_CANCEL_DEFERRED)
        rc = pthread_setcanceltype(*oldtype, &dont_care);
    return rc;
}

另一种状态是PTHREAD_CANCEL_ENABLE,另一种是PTHREAD_CANCEL_ASYNCHRONOUS

macOS 上这些函数的手册页确实说允许为旧 state/type 传递空指针,因此可以消除 macOS 上的 dont_care 变量。但是,POSIX 规范和 (RHEL 7.4) Linux 上的手册页都没有说空指针是允许的。上面的代码应该可以在这两个平台上安全运行。

该代码还侵入了保留供实现使用的命名空间——实现可以选择添加 pthread_getcancelstate()pthread_getcanceltype() 中的一个或两者(具有相同或不同的接口)和别无选择,只能重命名上面显示的函数。添加 _np (不可移植)后缀可能也无济于事;实现可以选择使用带有后缀的名称。