Basic problem, but haven't been able to find solution. I need .notify_one() to be picked up by DERIVED_TWO, I've tested the code within the same class and it works fine?
#include <mutex>
class BASE
{
public:
std::mutex(mu);
std::condition_variable condition;
};
class DERIVED_ONE:public BASE
{
public:
auto DoStuff()->void
{
std::unique_lock<mutex> lock(mu);
//Do Stuff here...
lock.unlock();
condition.notify_one();
}
};
class DERIVED_TWO:public BASE
{
public:
auto DoMoreStuff()->void
{
std::unique_lock<mutex> lock(mu);
condition.wait(lock);
//Do even more stuff...
lock.unlock();
}
};
SIDE NOTE:
I could use a polymorphic object to pass messages between classes, although this seems a messy solution
Different instances of your classes will not share the same condition variable object unless you declare it static. And I also doubt that you would want them to.
I would implement a separate message queue class that could be instantiated as communication channels as needed and passed to the instances of your other classes at creation time.
Related
I have a class where I want to call a method in a thread.
My methods don't modify the class attributs so I expect them to be const, but they instantiate a thread, so they can't.
What is the best choice between putting the std::thread mutable, remove the const because of the thread, edit : or using detached threads ?
class ValidationSound
{
public:
[... CTOR DTOR ...]
void emitSuccessSoundAsync() const
{
if(m_thread.joinable())
{
m_thread.join();
}
m_thread = std::thread(&ValidationSound::emitSound, this, std::cref(m_bipsParameters.first));
};
void emitFailureSoundAsync() const
{
if(m_thread.joinable())
{
m_thread.join();
}
m_thread = std::thread(&ValidationSound::emitSound, this, std::cref(m_bipsParameters.second));
};
void emitSound(const BipParameters& bipParam) const
{
//BIP BIP THE BUZZER
};
private:
std::pair<BipParameters, BipParameters> m_bipsParameters;
mutable std::thread m_thread;
};
My methods don't modify the class attributs so I expect them to be const, but they instantiate a thread, so they can't.
But your methods do modify class attributes. Your std::thread is a class attribute and once any of your methods are called, that attribute will change (begin running) and continue to change state even after the methods have exited.
What is the best choice between putting the std::thread mutable, remove the const because of the thread, edit : or using detached threads ?
In this case, I'd recommend removing the const from method signatures. Const just confuses the interface and could fool users into thinking it's thread-safe. If the methods were mutex protected and blocked for the duration of the thread execution time, you could make a stronger argument for mutable and const, but given your current implementation I wouldn't.
Edit: Said another way, imagine you've gone ahead and created a single const instance of you ValidationSound class. It would be very easy for a user of this class to call your instance in a way that creates many threads all playing different sounds interleaved at different times. Is that how you'd envision a const instance of this class behaving? It's certainly not how I'd envision it looking purely at the interface.
I'm making a game engine and I'm using libraries for various tasks. For example, I use FreeType which needs to be initialized, get the manager and after I don't use it I have to de-initialize it. Of course, it can only be initialized once and can only be de-initialized if it has been initialized.
What I came up with (just an example, not "real" code [but could be valid C++ code]):
class FreeTypeManager
{
private:
FreeTypeManager() {} // Can't be instantiated
static bool initialized;
static TF_Module * module; // I know, I have to declare this in a separate .cpp file and I do
public:
static void Initialize()
{
if (initialized) return;
initialized = true;
FT_Initialize();
FT_CreateModule(module);
}
static void Deinitialize()
{
if (!initialized) return;
initialized = false;
FT_DestroyModule(module);
FT_Deinit();
}
};
And for every manager I create (FreeType, AudioManager, EngineCore, DisplayManager) it's pretty much the same: no instances, just static stuff. I can see this could be a bad design practice to rewrite this skeleton every time. Maybe there's a better solution.
Would it be good to use singletons instead? Or is there a pattern suiting for my problem?
If you still want the singleton approach (which kind of makes sense for manager-type objects), then why not make it a proper singleton, and have a static get function that, if needed, creates the manager object, and have the managers (private) constructor handle the initialization and handle the deinitialization in the destructor (though manager-type objects typically have a lifetime of the whole program, so the destructor will only be called on program exit).
Something like
class FreeTypeManager
{
public:
static FreeTypeManager& get()
{
static FreeTypeManager manager;
return manager;
}
// Other public functions needed by the manager, to load fonts etc.
// Of course non-static
~FreeTypeManager()
{
// Whatever cleanup is needed
}
private:
FreeTypeManager()
{
// Whatever initialization is needed
}
// Whatever private functions and variables are needed
};
If you don't want a singleton, and only have static function in the class, you might as well use a namespace instead. For variables, put them in an anonymous namespace in the implementation (source) file. Or use an opaque structure pointer for the data (a variant of the pimpl idiom).
There's another solution, which isn't exactly singleton pattern, but very related.
class FreeTypeManager
{
public:
FreeTypeManager();
~FreeTypeManager();
};
class SomeOtherClass
{
public:
SomeOtherClass(FreeTypeManager &m) : m(m) {}
private:
FreeTypeManager &m;
};
int main() {
FreeTypeManager m;
...
SomeOtherClass c(m);
}
The solution is to keep it ordinary c++ class, but then just instantiate it at the beginning of main(). This moves initialisation/destruction to a little different place. You'll want to pass references to FreeTypeManager to every class that wants to use it via constructor parameter.
Note that it is important that you use main() instead of some other function; otherwise you get scoping problems which require some thinking how to handle..
I am currently working on a piece of code written by a former colleague which utilizes OpenMP. Myself however has no experience with OpenMP and while I understand the very basics by just reading his code, I'm currently stuck figuring out how to declare a threadlocal member for my own modification.
The current code in a very simplified version looks like this:
struct Worker
{
void work() { //... }
};
-------------------------------------------------------------------
Worker worker;
#pragma omp parallel for
for (int i = 0; i < n; ++i)
{
worker.work();
}
What I want to acheive is to modify the Worker class in a way similiar to this:
struct Worker
{
void work() { // m_var is accessed here }
int m_var; // should be threadlocal
};
However I have no clue how to achieve this using OpenMP. Notice that all other members inside Worker should not be synchronized or threadlocal.
PS: For those who are curious, Worker is actually a class to download some complicated stuff and in the for loop the single downloads are performed. m_var is going to be an object holding a session.
Non-static data members have separate instances in each instance of the class and cannot be thread-local - they inherit the sharing class of the concrete object of the given class. For example, if an object of class Worker is created on the stack of an OpenMP thread (i.e. the object has an automatic storage class), then the object itself is private to that thread and worker.m_var is also private. If the object is created on the heap, it could be shared with other threads and worker->m_var will then be shared too.
Thread-private can only be applied to data members with static storage class:
struct Worker
{
void work();
static int m_var;
#pragma omp threadprivate(m_var)
};
int Worker::m_var;
In that case only one static (global) copy of Worker::m_var exists and it making it thread-private gives each thread a separate instance shared between all instances of Worker in that thread.
Also note that private and firstprivate cannot be applied to class data members, no matter if they are static or not - see this answer.
Should the static requirement be unacceptable for your situation, you can to replace your int field with a class of its own -- the class can be private to your Worker, or you can make it a template to be reused with different fields in different classes.
Either way, the new class's constructor will allocate an array -- as long as there are OpenMP-threads (let's call it int_array):
ThreadedInt() {
int_array = new int[omp_get_max_threads()];
}
You will also implement the operators necessary to cast this new class into the original type (int in your example). For example:
operator int() const {
return int_array[omp_get_thread_num()];
}
as well as some others, such as assignment:
int& operator = (int value) {
return int_array[omp_get_thread_num()] = value;
}
then the rest of your code can remain unmodified, OpenMP or not.
I have the following problem: I have a class that needs to be protected from simultaneous access from different threads. The class has two methods: lock() and unlock() using (g_mutex_lock / g_mutex_unlock with a per-object GMutex). Now a locking method looks like this:
void Object::method()
{
lock();
// do stuff modifying the object
unlock();
}
Now lets assume that I have two mwthods of this type, method1() and method2() which I call one after another:
object.method1();
// but what if some other thread modifies object in between
object.method2();
I tried locking the object before this block und unlocking it again, but in this case
there is a deadlock even with a single thread because the GMutex doesn't know that it has already been locked by the same thread. A solution would be to modify the method to accept an additional bool to determine whether the object is already locked. But is there a more elegant concept? Or is this a shortcoming regarding the design concept in total?
The recursive mutex solution mentioned in other responses and comments will work just fine, but in my experience it leads to code that is harder to maintain, because once you switch to a recursive mutex it is all too easy to abuse it and lock all over the place.
Instead, I prefer to reorganize the code so that locking once is sufficient. In your example I would define the class as follows:
class Object {
public:
void method1() {
GMutexLock scopeLock(&lock);
method1_locked();
}
void method2() {
GMutexLock scopeLock(&lock);
method2_locked();
}
void method1_and_2() {
GMutexLock scopeLock(&lock);
method1_locked();
method2_locked();
}
private:
void method1_locked();
void method2_locked();
GMutex lock;
};
The "locked" versions of your methods are private, so they are only accessible from inside the class. The class takes responsibility in never calling these without the lock taken.
From the outside you have three choices of methods to call, depending on which of the methods you want to run.
Note that another improvement I've made is to not use explicit locking primitives but instead use the scope indirectly to lock and unlock. This is what GMutexLock does. An example implementation for this class is below:
class GMutexLock {
private:
GMutex* m;
GMutexLock(const GMutexLock &mlock); // not allowed
GMutexLock &operator=(const GMutexLock &); // not allowed
public:
GMutexLock(GMutex* mutex) {
m = mutex;
g_mutex_lock(m);
}
~GMutexLock() {
g_mutex_unlock(m);
}
};
Look up "recursive mutex" or "reentrant mutex" (versus the non-recursive mutex you're using now). These enable what you want. Some folks are not fans of recursive mutexes and feel they enable messy design.
Note that a recursive mutex cannot be locked on one thread and unlocked on another.
I personally would never use recursive mutexes (especially as such).
I would do some private functions that doesn't lock mutexes and lock around them in public functions' implementations.
I have a function in my class that creates a thread and gives it arguments to call a function which is part of that class but since thread procs must be static, I can't access any of the class's members. How can this be done without using a bunch of static members in the cpp file to temporarily give the data to be manipulated, this seems slow.
Heres an example of what I mean:
in cpp file:
void myclass::SetNumber(int number)
{
numberfromclass = number;
}
void ThreadProc(void *arg)
{
//Can't do this
myclass::SetNumber((int)arg);
}
I can't do that since SetNumber would have to be static, but I instance my class a lot so that won't work.
What can I do?
Thanks
Usually you specify the address of the object of myclass as arg type and cast it inside the ThreadProc. But then you'll be blocked on how passing the int argument.
void ThreadProc(void *arg)
{
myclass* obj = reinterpret_cast<myclass*>(arg);
//Can't do this
obj->SetNumber(???);
}
As you said this is maybe not only a bit slow but it also clutters the code. I would suggest to use boost::bind for argument binding and to create the threads in an os independent way (for your own source at least) you could use boost::thread. Then no need for static methods for your threads.
Now in the C++0x standard, here a small tutorial
I would suggest you to make a friendly class with a static method for this purpose. It looks much cleaner. Eg:-
class FriendClass
{
public:
static void staticPublicFunc(void* );
};
Now befriend the above class in your main class ...
class MyClass
{
friend void FriendClass::staticPublicFunc(void*);
};
This should enable you to set the friend-function as the thread-function and access the class per instance in each thread. Make sure to synchronize your access to data visible across threads.