1
votes

I want to achieve following kind of scenario using pthreads: There are two kinds of threads in a thread pool. First kind executes (say) fun1 second executes fun2. The main thread starts these two threads (for simplicity assume that there are only two worker threads in the pool each of the above two different kinds). The main thread then waits for one of the threads to finish. The first thread to finish notifies the main thread, the main thread then should notify the other worker thread to quit executing its job. And the cycle goes on.

Now if I wanted to stop a thread from executing its job, which can be like memmove/lock acquire, then I think it's best to just kill/cancel that thread and recreate it. What do you guys think?

Also if I cancel the thread (pthread_cancel) then it seems like I will have to call pthread_join to ensure it's actually canceled and then recreate it. Is that true?

Thanks, Nilesh.

1

1 Answers

2
votes

There is no such thing as killing a thread with pthreads. As you've found, there's cancellation, but it's up to the thread whether it acts on cancellation. Cancellation will only be acted upon if (1) it hasn't been blocked with pthread_setcancelstate(PTHREAD_CANCEL_DISABLE); and (2) the thread calls a function which is a cancellation point.

You're also right about needing to use some sort of synchronization operation to ensure the cancellation has been acted upon. One way to do this would be calling pthread_join on the thread, but that could be problematic if another point in your program might already be calling pthread_join on it (calling pthread_join twice invokes UB!). In this case you could install a cancellation cleanup handler that posts to a semaphore or signals a condition variable when it runs, and wait for the notification that way.