user1002288
user1002288

Reputation: 5040

For a Multithreading program, if one thread dies how you can know that ?

For a Multithreading program, if one thread dies how you can know that ?

My idea:

(1) use ps to check LWP but it is manually, not efficient. (2) set a try-catch in each thread, if it exit non-normally, catch it. (3) let the dying-thread send a message to std::cout or main thread.

Other better ideas ?

thanks

Upvotes: 3

Views: 714

Answers (2)

A.H.
A.H.

Reputation: 66263

You could use pthread_cleanup_push(3) at a very early stage in the thread function. The function given to pthread_cleanup_push could set some flag which a "watcher" thread can pick up. pthread_cleanup_push is also honoured by pthread_exit and is not bound to exceptions.

Edit: A second way to do this: Use pthread_key_create(3) with a destructor function and call pthread_setspecific(3) early in the thread function. The destructor function can signal the watching thread it's imminent death.

Upvotes: 4

thiton
thiton

Reputation: 36049

You could simply use pthread_cleanup_push and pthread_cleanup_pop to execute a cleanup handler on thread exit. This would catch cancellation/pthread_exit events.

Upvotes: 1

Related Questions