【编译工具】之Andorid pthread_cancel函数

1. Android编译含多线程的代码
1.1 编译错误
error: implicit declaration of function 'pthread_cancel' [-Werror=implicit-function-declaration]
1.2 错误原因

Android NDK在v5版本后不再提供全部的POSIX线程库的API(比如pthread_cancel和pthread_setcancelstate)。原因之一是线程被标记结束后不一定会把自己拥有的资源释放掉,甚至不一定会结束,因此很可能造成内存泄露或死锁等问题,而这些问题在移动设备上更加突出[1]。
比较安全的方法是使用更安全pthread_kill函数代替,有关pthread_kill的功能讲解和替换方式可以参考:
https://blog.csdn.net/darkengine/article/details/7106207

1.3 解决办法
#define SIG_CANCEL_SIGNAL SIGUSR1
#define PTHREAD_CANCEL_ENABLE 1
#define PTHREAD_CANCEL_DISABLE 0

typedef long pthread_t;

static int pthread_setcancelstate(int state, int *oldstate) {
    sigset_t   new, old;
    int ret;
    sigemptyset (&new);
    sigaddset (&new, SIG_CANCEL_SIGNAL);

    ret = pthread_sigmask(state == PTHREAD_CANCEL_ENABLE ? SIG_BLOCK : SIG_UNBLOCK, &new , &old);
    if(oldstate != NULL)
    {
        *oldstate =sigismember(&old,SIG_CANCEL_SIGNAL) == 0 ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE;
    }
    return ret;
}

static inline int pthread_cancel(pthread_t thread) {
    return pthread_kill(thread, SIG_CANCEL_SIGNAL);
}

参考网址:https://www.jianshu.com/p/ee417102d7fc

你可能感兴趣的:(【编译工具】)