2013-04-30 88 views
0

我正在將一個現有的C++項目移植到objective-C++,並遇到了這個互斥量的東西。如果它是正確的,我不確定這裏做了什麼。要初始化某種多線程鎖機構(稱爲 「CriticalSection的」)以下完成:iOS使用pthread_mutexattr_t故障

#include <pthread.h> 

pthread_mutex_t cs; 
pthread_mutexattr_t attr; 

在後面的代碼:

pthread_mutexattr_init(&attr); 
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); 
pthread_mutex_init(&cs, &attr); 

進入 「鎖定」 有:

pthread_mutex_lock(&cs); 

離開了 「鎖」:

pthread_mutex_unlock(&cs); 
pthread_mutex_destroy(&cs); 

我的問題(因爲我不知道這是如何完成的)是:這看起來像一個正確的實現? 因爲我遇到的問題看起來像鎖機制不起作用(錯誤的內存訪問錯誤,在使用「CriticalSection」的情況下損壞的指針)。

回答

0

這是正確的,除非你不想在解鎖時破壞互斥鎖。只有在可以確保所有線程都完成後才能破壞互斥鎖。

例如:

class CriticalSection 
{ 
public: 
    CriticalSection() 
    { 
     pthread_mutexattr_t attr; 
     pthread_mutexattr_init(&attr); 
     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); 
     pthread_mutex_init(&mutex, &attr); 
    } 
    ~CriticalSection() { pthread_mutex_destroy(&mutex); } 
    void Enter() { pthread_mutex_lock(&mutex); } 
    void Leave() { pthread_mutex_unlock(&mutex); } 
private: 
    pthread_mutex_t mutex; 
};