【发布时间】:2012-08-16 06:06:28
【问题描述】:
这是我到目前为止所做的:
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 标准库中提供的锁类?
-
“在 DIY 互斥锁类中应该提供哪些其他功能?”是一个非常主观的问题,“可能会引发辩论、争论、投票或扩展讨论”——因此投票结束是非建设性的。
-
@JoachimPileborg 我不知道 C++ 标准有任何互斥锁类!我之前确实在谷歌上搜索过。我再看看。
-
@paxdiablo 我应该如何修改这个问题以使其具体化?
-
参见例如
std::lock_guard。这些在 C++11 标准中是新的,所以如果你有一个旧的编译器,它可能不支持它。 VC++ 2010 应该有它,还有 GCC 4.4。
标签: c++ multithreading pthreads mutex