linux - pthread_cancel 和取消点

标签 linux multithreading

我正在学习 pthread_cancel 函数并测试线程是否会在未达到取消点时被取消。线程由默认属性创建,并使其在添加循环中运行。但是当发送取消请求并且线程立即退出时。它没有达到取消点,我认为它不应该立即响应请求。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_func(void *arg)
{
    int i;
    int j;
    int k;

    k = 1;

    /* add operation */
    for (i=0; i<1000; ++i) {       
        for (j=0; j<10000;++j) {
             ++k;              // maybe for(z=0; z<10000; ++z) added would 
                               // be better
        }
    }
    return (void *)10;
}

int main(void)
{
    char *retval;
    pthread_t tid;

    if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {                 
        printf("create error\n");
    }

    if (pthread_cancel(tid) != 0) { // cancel thread
        printf("cancel error\n");
    }
    pthread_join(tid, (void **)retval); 
    printf("main thread exit\n");
    return 0;
}

最佳答案

要有一个“取消点”,您需要使用 pthread_setcancelstate() 在您的线程函数开始时禁用取消,然后在需要时启用它。生成新线程时,它的取消状态为“已启用”,这意味着它可以随时立即取消。

也许更重要的是,您可能根本不应该使用 pthread_cancel()。有关更多信息,请参见此处:Cancelling a thread using pthread_cancel : good practice or bad

关于linux - pthread_cancel 和取消点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34377260/

相关文章:

linux - 缺少 time.h 的 lib 文件

c - C中父进程退出时杀死子进程

java - 传递给 List 的 ArrayAdapter 的 arraylist 应该是线程安全的吗?

c++ - dlopen 期间 undefined symbol

c# - 使用来自 C# .NET 的 OCX 的线程安全

java - 我如何实现文件扫描器的多线程场景?

java - 多线程httpClient

linux - 管道参数 : echo "value1 value2" | command $1 $2

python - 如何允许 python 应用程序更改系统时间

linux - 在 Linux 上批量重命名具有修改时间戳的文件