Я создаю нить и помещаю ее в бесконечный цикл. Я получаю утечки памяти при проверке кода с помощью 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)
, но я все еще получаю утечки.
Несколько небольших мыслей:
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).
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.)