C语言 取消循环中的 pthread



我有一个大约 6 个线程 id 的数组,我想在一个循环中取消。这是因为我面临着某些 seg 错误,因为这些线程在清理后试图访问一些无效内存。 当我将取消类型更改为 asynchronous 时,即使在线程取消后,我仍然不断收到分段错误。如果我将取消类型更改为 deferred 并将取消点保留为 pthread_join ,则在 2 个线程取消后,我的代码被 join 阻止并且它不会退出。

你能建议问题是什么吗?

/* The cancel type is deferred and cancellation point is pthread_join. After 2    
iterations, it is unable to come out of join and gets blocked.   Here is the code:*/ 
for (int i=0;i<N_BATCH_THREADS;i++)
{
    rc = pthread_cancel(g_batch_th[i]);
    if(rc!=0)
    {
        fprintf(stderr,"Error in pthread canceln");
        exit(1);
    }
    else 
    {
        fprintf(stderr,"Thread cancelled successfully %dn",g_batch_th[i]);
    }
    rc = pthread_join(g_batch_th[i],&status);
    if(rc!=0) 
    {
        fprintf(stderr,"Error in pthread joinn");
        exit(1);
    }
    else 
    {
        fprintf(stderr,"Return from pthread join successful %dn",g_batch_th[i]);
    }
    if( status != PTHREAD_CANCELED) 
    {
        fprintf(stderr,"Unexpected thread status n");
        exit(1);
    }
}
我想

你误解了延迟取消。在您的代码示例中,调用 pthread_join 的线程取消其他线程不会"调用"其他线程的取消。相反,当取消的线程调用取消点时,它实际上终止了。

另一方面,当您使用异步取消时,线程终止确实或多或少会立即发生,但实际上只是或多或少。线程终止不能保证在pthread_cancel返回之前发生,因此取消的线程可能会继续运行一些非常短的时间,并且在正确终止之前有时间段错误。也可能是它们注册了线程取消回调,这可能也会出现段错误。当然,如果不了解细节,我就不能谈论细节。

最新更新