是否更改另一个线程的pthread取消类型



我想要完成的是,主线程首先在工作线程上尝试正常的延迟取消(执行代码,出于我的目的,这是一个黑匣子(,然后如果线程在超时(pthread_timedjoin_np()(后仍在运行,我想进行异步取消。我遇到的问题是pthread_setcanceltype()只用于调用线程。有什么变通方法或破解方法可以让我这么做吗?我想避免使用信号,因为至少在Linux下,异步取消似乎仍然会执行线程对象的C++析构函数,这对我来说很重要

在某些情况下,pthread_setcanceltype()实际上必须执行取消操作(请参阅下面的源代码(。所以,这就是为什么没有pthread_setcanceltype_for_thread()的原因。实际的取消类型是pthread结构中的字段,必须以原子方式更改。

ftp://sources.redhat.com/pub/glibc/snapshots/glibc-latest.tar.bz2/glibc-20090518/nptl/pthread_setcanceltype.c

__pthread_setcanceltype (type, oldtype)
     int type;
     int *oldtype;
{
  volatile struct pthread *self;
  self = THREAD_SELF;
  int oldval = THREAD_GETMEM (self, cancelhandling);
  while (1)
    {
      int newval = (type == PTHREAD_CANCEL_ASYNCHRONOUS
                    ? oldval | CANCELTYPE_BITMASK
                    : oldval & ~CANCELTYPE_BITMASK);
      /* Store the old value.  */
      if (oldtype != NULL)
        *oldtype = ((oldval & CANCELTYPE_BITMASK)
                    ? PTHREAD_CANCEL_ASYNCHRONOUS : PTHREAD_CANCEL_DEFERRED);
      /* Update the cancel handling word.  This has to be done
         atomically since other bits could be modified as well.  */
      int curval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling, newval,
                                              oldval);
      if (__builtin_expect (curval == oldval, 1))
        {
          if (CANCEL_ENABLED_AND_CANCELED_AND_ASYNCHRONOUS (newval))
            {
              THREAD_SETMEM (self, result, PTHREAD_CANCELED);
              __do_cancel ();  // HERE THE CANCELLING
            }
          break;
        }
      /* Prepare for the next round.  */
      oldval = curval;
    }
  return 0;
}
strong_alias (__pthread_setcanceltype, pthread_setcanceltype)

如果你非常需要从外部更改canceltype,你可以破解库并直接设置字段。

PS:用于NPTL(Linux上glibc中pthreads的当前实现(了解如何从int pthread_t获取struct pthread的最简单方法是。。。pthread_join:

 pthread_join (pthread_t threadid, thread_return) 
 { 
     struct pthread *pd = (struct pthread *) threadid;