简体   繁体   中英

Why destroy pthread_cond_t and pthread_mutex_t?

If in a threaded code, I create a pthread_cond_t c; condition variable or a mutex pthread_mutex_t m; in C, it is advised to destroy them after all the work is done.

Why is it so?

Also why is it utmost necessary to destroy a cond variable if it was dynamically initialized using pthread_cond_init(); function.

To quote from David Butenhof " Programming with POSIX Threads "

"When you dynamically initialize a condition variable, you should destroy the condition variable when you no longer need it, by calling pthread_cond_destroy.You do not need to destroy a condition variable that was statically initialized using the PTHREAD_COND_INITIALIZER macro"

pthread_cond_t and pthread_mutex_t are regarded as resources.

You need to destroy/cleanup/close resources when you are done with them, much like you need to close a file or free memory when you're done with them. Failure to do so results in a resource leak, and you may run out of theses resources.

Treating these as a resources gives the implementation more freedom on how to implement them, and on some particular implementation, there may be no harm in forgetting to _destroy() them, others may connect the mutex/condition variable to a kernel resource that needs to be cleaned up when you don't need it anymore. The rationale section of pthread_mutex_init gives some more overview, and the same applies to condition variables

If you initialize a condition variable with PTHREAD_COND_INITIALIZER, you're supposed to initialize a statically allocated mutex ie it is going to live until the application ends, at which point it will be destroyed by the system, presumably that's what the author meant. That applies to mutex/cond variables that is dynamically initialized as well, the system will clean those up as well.

Most resources are automatically cleaned up when an application ends, so whether it's good practice to clean up everything manually or just let the system do it in such case is another discussion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM