线程取消后程序卡住
Program get stuck after thread cancellation
在这里,我创建了 10 个线程并在它们的函数中取消了这些线程。但有时,程序经常会卡住,没有响应。当我查看系统监视器时,我看到等待通道是 futex_wait_queue_me。是什么原因 ?很少,我遇到分段错误,这可能是相关的吗?我知道,pthread_cancel 函数有可能与无效线程一起运行,例如已经取消的线程或未初始化的线程,但我无法理解死锁或分段错误。
pthread_t th[10];
void cancel()
{
for (int i = 0; i < 10; ++i)
pthread_cancel(th[i]);
}
void* thf(void * arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
cancel();
}
int main(int argc, char const *argv[])
{
for (int i = 0; i < 10; ++i)
pthread_create(&th[i],NULL,thf,NULL);
for (int i = 0; i < 10; ++i)
pthread_join(th[i],NULL);
return 0;
}
您的 cancel()
函数每次被调用时都会取消所有线程,而不仅仅是活动线程,我猜这不是我们想要的。它还可以在未初始化的线程对象上调用 pthread_cancel()
(例如,如果第一个线程在其他线程全部创建之前调用 cancel()
)。这就是死锁和段错误的来源。
如果只想取消当前线程,可以使用pthread_cancel(pthread_self())
。
在这里,我创建了 10 个线程并在它们的函数中取消了这些线程。但有时,程序经常会卡住,没有响应。当我查看系统监视器时,我看到等待通道是 futex_wait_queue_me。是什么原因 ?很少,我遇到分段错误,这可能是相关的吗?我知道,pthread_cancel 函数有可能与无效线程一起运行,例如已经取消的线程或未初始化的线程,但我无法理解死锁或分段错误。
pthread_t th[10];
void cancel()
{
for (int i = 0; i < 10; ++i)
pthread_cancel(th[i]);
}
void* thf(void * arg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
cancel();
}
int main(int argc, char const *argv[])
{
for (int i = 0; i < 10; ++i)
pthread_create(&th[i],NULL,thf,NULL);
for (int i = 0; i < 10; ++i)
pthread_join(th[i],NULL);
return 0;
}
您的 cancel()
函数每次被调用时都会取消所有线程,而不仅仅是活动线程,我猜这不是我们想要的。它还可以在未初始化的线程对象上调用 pthread_cancel()
(例如,如果第一个线程在其他线程全部创建之前调用 cancel()
)。这就是死锁和段错误的来源。
如果只想取消当前线程,可以使用pthread_cancel(pthread_self())
。