[英]destroy std::mutex vs pthread_mutex_t
CPP 中的 std::mutex 和 pthread_mutex_t 有什么區別?
當按如下方式動態分配互斥鎖類型時,銷毀它們的正確方法是什么:
pthread_mutex_t * mutex1 = new pthread_mutex_t();
std::mutex * mutex2 = new std::mutex ();
區別在於它們來自不同的庫。 它們都是互斥體(mutices?)。
pthread_mutex
來自為 C 設計的庫,因此它不使用構造函數或析構函數。 簡單地創建一個pthread_mutex_t
object不會創建一個 mutex 。 您必須調用pthread_mutex_init
來創建互斥體。 同樣,您必須調用pthread_mutex_destroy
來銷毀它,因為它沒有執行此操作的析構函數。
std::mutex
是為 C++ 設計的,所以當然 object 本身始終充當互斥鎖,不需要單獨的 function 調用。
pthread_mutex_t * mutex1 = new pthread_mutex_t; // () not needed
// you created a pthread_mutex_t object, but didn't initialize it.
// You created it with new, so destroy it with delete:
delete mutex1;
pthread_mutex_t * mutex1 = new pthread_mutex_t; // () not needed
// you created a pthread_mutex_t object
pthread_mutex_init(&mutex1, nullptr); // can check return value for errors
// and used that space to store whatever data a mutex has in it (perhaps pthread_mutex_init allocates other memory)
// Reverse pthread_mutex_init with pthread_mutex_destroy:
pthread_mutex_destroy(&mutex1); // can check return value for errors
// You created it with new, so destroy it with delete:
delete mutex1;
std::mutex * mutex3 = new std::mutex; // () not needed
// You created it with new, so destroy it with delete
delete mutex3;
但是,您不需要使用new
分配所有內容。 C++ 不是 Java。如果你想要一個 object,那么在絕大多數情況下你可以只擁有一個:
std::mutex mutex4;
// automatically destroyed when it goes out of scope
和 C 版本:
pthread_mutex_t mutex5;
pthread_mutex_init(&mutex5, nullptr); // can check return value for errors
// Reverse pthread_mutex_init with pthread_mutex_destroy:
pthread_mutex_destroy(&mutex5); // can check return value for errors
// Variable is destroyed when it goes out of scope.
// Of course you can reuse the same variable for a new mutex by calling init again
// and destroy when you are done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.