Kill Thread in Pthread Library

前端 未结 5 507
谎友^
谎友^ 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条回答
  •  再見小時候
    2020-11-27 05:24

    There are two approaches to this problem.

    • Use a signal: The thread installs a signal handler using sigaction() which sets a flag, and the thread periodically checks the flag to see whether it must terminate. When the thread must terminate, issue the signal to it using pthread_kill() and wait for its termination with pthread_join(). This approach requires pre-synchronization between the parent thread and the child thread, to guarantee that the child thread has already installed the signal handler before it is able to handle the termination signal;
    • Use a cancellation point: The thread terminates whenever a cancellation function is executed. When the thread must terminate, execute pthread_cancel() and wait for its termination with pthread_join(). This approach requires detailed usage of pthread_cleanup_push() and pthread_cleanup_pop() to avoid resource leakage. These last two calls might mess with the lexical scope of the code (since they may be macros yielding { and } tokens) and are very difficult to maintain properly.

    (Note that if you have already detached the thread using pthread_detach(), you cannot join it again using pthread_join().)

    Both approaches can be very tricky, but either might be specially useful in a given situation.

提交回复
热议问题