Как я могу убить pthread, который находится в бесконечном цикле, из-за пределов этого цикла?

Я создаю нить и помещаю ее в бесконечный цикл. Я получаю утечки памяти при проверке кода с помощью valgrind. Вот мой код:

#include <pthread.h>
#include <time.h>

void thread_do(void){
    while(1){}
}

int main(){
    pthread_t th;   
    pthread_create(&th, NULL, (void *)thread_do, NULL);

    sleep(2);
    /* I want to kill thread here */
    sleep(2);
    return 0;
}

Итак, поток создается в main и просто постоянно запускается thread_do(). Есть ли способ убить его изнутри main через 2 секунды? Я пробовал оба pthread_detach(th) и pthread_cancel(th), но я все еще получаю утечки.

24
задан Pithikos 31 October 2011 в 23:41
поделиться

1 ответ

Несколько небольших мыслей:

  1. Вы пытаетесь отменить свою ветку, но если действующая политика отмены предназначена для отложенной отмены, ваша thread_do() никогда не будет отменена, потому что она никогда не вызывает функции, которые являются точками отмены:
    A thread's cancellation type, determined by
    pthread_setcanceltype(3), may be either asynchronous or
    deferred (the default for new threads).  Asynchronous
    cancelability means that the thread can be canceled at any
    time (usually immediately, but the system does not guarantee
    this).  Deferred cancelability means that cancellation will
    be delayed until the thread next calls a function that is a
    cancellation point.  A list of functions that are or may be
    cancellation points is provided in pthreads(7).
  1. Вы не присоединяетесь к потоку в своем простом примере кода; позвоните pthread_join(3) до окончания вашей программы:
    After a canceled thread has terminated, a join with that
    thread using pthread_join(3) obtains PTHREAD_CANCELED as the
    thread's exit status.  (Joining with a thread is the only way
    to know that cancellation has completed.)
6
ответ дан 28 November 2019 в 23:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: