P
petru.marginean
Hello,
I would like to re-implement this function that currently uses
pthreads:
pthread_mutex_t mutex;
int i = pthread_mutex_init(&mutex, 0);
void MutexCB(int lock)
{
if (lock)
pthread_mutex_lock(&mutex);
else
pthread_mutex_unlock(&mutex);
}
using the boost library.
So the function has to lock the mutex if 'lock' == true, unlock it
otherwise. It has to be thread safe as well.
I had difficulties since the scoped_lock is NOT thread safe, and the
access to the mutex's do_lock()/do_unlock() methods is private.
Regards,
Petru
P.S. Here is a solution I found. It uses:
- recursive mutex,
- a static lock that gives the access to the lock/unlock mechanism (no
d-tor call during the operations) and
- another lock (on the stack) that makes the static lock thread safe.
boost::recursive_mutex m;
void MutexCB(int lock)
{
boost::recursive_mutex::scoped_lock l(m); // it makes the 's'
lock thread safe
static boost::recursive_mutex::scoped_lock s(m, false /*lock
later only if necessary*/);
if (lock)
s.lock();
if (!lock)
s.unlock();
}
As you can see it is more complicated that the pthread solution. is
there possible to write a solution at least as simple as the pthreads
one?
I would like to re-implement this function that currently uses
pthreads:
pthread_mutex_t mutex;
int i = pthread_mutex_init(&mutex, 0);
void MutexCB(int lock)
{
if (lock)
pthread_mutex_lock(&mutex);
else
pthread_mutex_unlock(&mutex);
}
using the boost library.
So the function has to lock the mutex if 'lock' == true, unlock it
otherwise. It has to be thread safe as well.
I had difficulties since the scoped_lock is NOT thread safe, and the
access to the mutex's do_lock()/do_unlock() methods is private.
Regards,
Petru
P.S. Here is a solution I found. It uses:
- recursive mutex,
- a static lock that gives the access to the lock/unlock mechanism (no
d-tor call during the operations) and
- another lock (on the stack) that makes the static lock thread safe.
boost::recursive_mutex m;
void MutexCB(int lock)
{
boost::recursive_mutex::scoped_lock l(m); // it makes the 's'
lock thread safe
static boost::recursive_mutex::scoped_lock s(m, false /*lock
later only if necessary*/);
if (lock)
s.lock();
if (!lock)
s.unlock();
}
As you can see it is more complicated that the pthread solution. is
there possible to write a solution at least as simple as the pthreads
one?