C ++使用卡在函数调用中的辅助线程取消pthread

问题描述 投票:0回答:1

我在pthreads之一中设置超时时遇到麻烦。我在这里简化了代码,并且将问题隔离为正在线程中运行的CNF算法。

int main(){
  pthread_t t1;
  pthread_t t2;
  pthread_t t3; //Running multiple threads, the others work fine and do not require a timeout.

  pthread_create(&t1, nullptr, thread1, &args);
  pthread_join(t1, nullptr);

  std::cout << "Thread should exit and print this\n"; //This line never prints since from what I've figured to be a lack of cancellation points in the actual function running in the thread.

  return  0;
}

void* to(void* args) {
    int timeout{120};
    int count{0};
    while(count < timeout){
        sleep(1);
        count++;
    }
    std::cout << "Killing main thread" << std::endl;
    pthread_cancel(*(pthread_t *)args);
}

void *thread1 (void *arguments){
  //Create the timeout thread within the CNF thread to wait 2 minutes and then exit this whole thread
  pthread_t time;
  pthread_t cnf = pthread_self();
  pthread_create(&time, nullptr, &timeout, &cnf);

  //This part runs and prints that the thread has started
  std::cout << "CNF running\n"; 
  auto *args = (struct thread_args *) arguments;

  int start = args->vertices;
  int end = 1;

  while (start >= end) {
     //This is where the issue lies 
     cover = find_vertex_cover(args->vertices, start, args->edges_a, args->edges_b); 

    start--;
  }

  pthread_cancel(time); //If the algorithm executes in the required time then the timeout is not needed and that thread is cancelled. 
  std::cout << "CNF END\n";
  return nullptr;
}

我尝试注释掉find_vertex_cover函数并添加了infinite loop,然后我可以创建timeout并以此方式结束线程。该功能实际上以应有的方式工作。在我正在运行的条件下运行它应该花费永远,因此我需要超时。

//This was a test thread function that I used to validate that implementing the timeout using `pthread_cancel()` this way works. The thread will exit once the timeout is reached.

void *thread1 (void *args) {
    pthread_t x1;
    pthread_t x2 = pthread_self();
    pthread_create(&x1, nullptr, to, &x2);

    /*
    for (int i = 0;i<100; i++){
        sleep(1);
        std::cout << i << std::endl;
    }
    */
}

使用此功能,我可以验证我的超时线程方法是否有效。问题是当find_vertex_cover运行后,当我实际运行CNF算法(在后台使用Minisat)时,没有办法结束线程。该算法在我正在实现的情况下可能会失败,这就是为什么要实现超时的原因。

我已经使用pthread_cancel()进行了阅读,虽然这不是一个好方法,但这是我可以实现超时的唯一方法。

在此问题上的任何帮助将不胜感激。

c++ linux multithreading concurrency pthreads
1个回答
0
投票

我已经阅读了使用pthread_cancel()的内容,虽然这不是一个好方法[..]

是的。应避免pthread_cancel尤其是在C ++中不好用,因为它与异常处理不兼容。您应该使用std::thread,并且对于线程终止,可以使用条件变量或原子变量,该变量在设置时终止“无限循环”。

此外,通过pthread_cancel进行的取消取决于两件事:1)取消状态2)取消类型。

默认取消状态为启用。但是默认取消类型是deferred-意味着取消请求将仅在下一个取消点发送。我怀疑find_vertex_cover中有任何取消点。因此,您可以通过调用将取消类型设置为asynchronous

pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

从您希望能够立即取消的线程中。

但是同样,我建议完全不要采用pthread_cancel方法,而是重写“取消”逻辑,以使其不涉及pthread_cancel

© www.soinside.com 2019 - 2024. All rights reserved.