這是我迄今所做的:創建在C互斥鎖櫃類++
class mutexLocker
{
private:
/* Declaration of a Mutex variable `mutexA`. */
pthread_mutex_t &mutexA;
/* `mutexStatus` holds the return value of the function`pthread_mutex_lock `.
This value has to be returned to the callee so we need to preserve it in a class
variable. */
int mutexStatus;
/* We need to decide how to deal with the situation when one thread tries to lock then
mutex repeatedly. If the mutex is of type recursive, then there won't be any problem for
sure, but otherwise the case may result in a deadlock. */
pthread_t calleeThreadId;
public:
/* Constructor attempts to lock the desired mutex variable. */
mutexLocker (pthread_mutex_t argMutexVariable, pthread_t threadId)
: mutexA (argMutexVariable, calleeThreadId)
{
/* Return value is needed in order to know whether the mutex has been
successfully locked or not. */
int mutexStatus = pthread_mutex_lock (&argMutexVariable);
}
/* Since the constructor can't return anything, we need to have a separate function
which returns the status of the lock. */
int getMutexLockStatus()
{
return mutexStatus;
}
/* The destructor will get called automatically whereever the callee's scope ends, and
will get the mutex unlocked. */
~mutexLocker()
{
pthread_mutex_unlock (&mutexA);
}
};
應在DIY互斥鎖櫃類中提供什麼其他功能?
是否有你想實現自己的原因而不是使用Boost或C++ 11標準庫中可用的鎖類? – 2012-08-16 06:10:11
「DIY互斥鎖類中應該提供哪些其他功能?」是一個非常主觀的問題,「可能會爭辯辯論,辯論,投票或擴大討論」 - 因此投票結束時不具有建設性。 – paxdiablo 2012-08-16 06:11:52
@JoachimPileborg我不知道C++標準有任何互斥鎖類!我以前在此搜索過Google。我會再看看。 – 2012-08-16 06:14:19