Ive been googling mutex tutorials / examples but cant seem to find one for the situation I need (or more likely I did, but just never realized how to apply it to my situation, as I don’t fully understand it at the moment).
I have a C++ dll that has 2 callback functions. The callback functions are called from a 3rd party program. Each call back function adds information to a global variable (separate global variables). There are 2 other functions that each use these global variables.
The 3rd party program has many threads, so the call back functions are being called all the time. The other 2 functions are manually called by the user. The global variables end up being accessed by 2 things at once and causes a crash.
right now the global variables are in a class like this
class Global
{
public:
static CString & get_allscores() { static CString get_allscores; return get_allscores; }
static CString & get_allplayers() { static CString allplayers; return allplayers; }
};
Could someone show me a quick example on how to use mutex with 2 functions that are both accessing one of those global variables ?
Thanks
EDIT:
What about a situation like this
CString allchat; //global variable
void function1()
{
allchat += "test";
}
void function2()
{
cout << allchat;
}
if those functions were being called by many threads repeatedly and out of order, can I add a mutex object to make it multi thread friendly?
so far my plan was to create a mutex with no owner when the program launches.. and then when each function is called itll take ownership and release it at the end of the function. is this the correct way of doing it?
With respect to the EDITed part of the answer: yes, if these are the only functions that access the global data, adding a mutex lock to both functions will make the code thread safe. The danger, of course, is forgetting, in the course of developing and maintaining the code, that this global data has to be protected with a mutex. Of course, the solution to that problem is to take the code as written and wrap it in a class, so that
allchatis a private member, adding a mutex to the class, and using the mutex from any member functions that accessallchat.