M
Marcel Müller
I have a mutex lock that is implemented as RAII. I need to acquire the
mutex as long as the constructor runs. But for the /entire/ constructor
run not just the construction of the derived class.
Example:
#include <stdio.h>
// some mutex class
class Mutex
{
public:
// hold the Mutex (RAII)
struct Lock
{ Lock(Mutex& mtx)
{ puts("Lock()\n");
//...
}
~Lock()
{ puts("~Lock()\n");
//...
}
};
//...
};
// set of configuration parameters
struct Parameters
{ //...
};
class WorkerBase
{ //...
protected:
WorkerBase(const Parameters& params)
{ // do something with params...
}
};
class Worker : public WorkerBase
{
private:
static Parameters GlobalParams;
static Mutex ParamMtx; // protect the above
public:
// synchronized public access to the parameters
struct AccessParams : Mutex::Lock
{ AccessParams() : Mutex::Lock(ParamMtx) {}
operator Parameters&() { return GlobalParams; }
};
Worker() : WorkerBase(AccessParams())
{ AccessParams params; // !!! Mutex acquired twice!
// do something with params...
}
};
Parameters Worker::GlobalParams;
Mutex Worker:aramMtx;
int main()
{ Worker worker;
// do something with worker...
}
As expected the mutex is acquired twice. But this is bad, since the idea
is to sample a consistent set of parameters and not to use one parameter
set for the base class and some other one for the derived class.
Any ideas how to solve this?
Marcel
mutex as long as the constructor runs. But for the /entire/ constructor
run not just the construction of the derived class.
Example:
#include <stdio.h>
// some mutex class
class Mutex
{
public:
// hold the Mutex (RAII)
struct Lock
{ Lock(Mutex& mtx)
{ puts("Lock()\n");
//...
}
~Lock()
{ puts("~Lock()\n");
//...
}
};
//...
};
// set of configuration parameters
struct Parameters
{ //...
};
class WorkerBase
{ //...
protected:
WorkerBase(const Parameters& params)
{ // do something with params...
}
};
class Worker : public WorkerBase
{
private:
static Parameters GlobalParams;
static Mutex ParamMtx; // protect the above
public:
// synchronized public access to the parameters
struct AccessParams : Mutex::Lock
{ AccessParams() : Mutex::Lock(ParamMtx) {}
operator Parameters&() { return GlobalParams; }
};
Worker() : WorkerBase(AccessParams())
{ AccessParams params; // !!! Mutex acquired twice!
// do something with params...
}
};
Parameters Worker::GlobalParams;
Mutex Worker:aramMtx;
int main()
{ Worker worker;
// do something with worker...
}
As expected the mutex is acquired twice. But this is bad, since the idea
is to sample a consistent set of parameters and not to use one parameter
set for the base class and some other one for the derived class.
Any ideas how to solve this?
Marcel