简体   繁体   English

为什么要破坏pthread_cond_t和pthread_mutex_t?

[英]Why destroy pthread_cond_t and pthread_mutex_t?

If in a threaded code, I create a pthread_cond_t c; 如果在线程代码中,我创建了一个pthread_cond_t c; condition variable or a mutex pthread_mutex_t m; 条件变量或互斥量pthread_mutex_t m; in C, it is advised to destroy them after all the work is done. 在C中,建议在完成所有工作后销毁它们。

Why is it so? 为什么会这样?

Also why is it utmost necessary to destroy a cond variable if it was dynamically initialized using pthread_cond_init(); 另外,为什么在使用pthread_cond_init();动态初始化cond变量时必须销毁它pthread_cond_init(); function. 功能。

To quote from David Butenhof " Programming with POSIX Threads " 引用David Butenhof“ 用POSIX线程编程

"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_destroy来销毁条件变量。你不需要销毁一个使用PTHREAD_COND_INITIALIZER宏静态初始化的条件变量”

pthread_cond_t and pthread_mutex_t are regarded as resources. pthread_cond_t和pthread_mutex_t被视为资源。

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. 将这些作为资源处理使得实现更加自由地实现它们,并且在某些特定实现上,忘记_destroy()它们可能没有坏处,其他人可能将互斥/条件变量连接到需要的内核资源。当你不再需要它时要清理干净。 The rationale section of pthread_mutex_init gives some more overview, and the same applies to condition variables pthread_mutex_init的基本原理部分提供了更多概述,同样适用于条件变量

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. 如果使用PTHREAD_COND_INITIALIZER初始化条件变量,则应该初始化静态分配的互斥锁,即它将一直存在直到应用程序结束,此时它将被系统销毁,可能是作者的意思。 That applies to mutex/cond variables that is dynamically initialized as well, the system will clean those up as well. 这适用于动态初始化的互斥锁/ cond变量,系统也会清理它们。

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. 当应用程序结束时,大多数资源会自动清理,因此,在这种情况下手动清理所有内容或仅让系统执行此操作是否是一种好的做法是另一种讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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