Kill Thread in Pthread Library

前端 未结 5 500
谎友^
谎友^ 2020-11-27 05:14

I use pthread_create(&thread1, &attrs, //... , //...); and need if some condition occured need to kill this thread how to kill this ?

5条回答
  •  -上瘾入骨i
    2020-11-27 05:41

    First store the thread id

    pthread_create(&thr, ...)
    

    then later call

    pthread_cancel(thr)
    

    However, this not a recommended programming practice! It's better to use an inter-thread communication mechanism like semaphores or messages to communicate to the thread that it should stop execution.

    Note that pthread_kill(...) does not actually terminate the receiving thread, but instead delivers a signal to it, and it depends on the signal and signal handlers what happens.

提交回复
热议问题