PDA

View Full Version : State variable used by multiple threads



bryang
27th April 2012, 22:09
Found the answer at: http://www.qtcentre.org/wiki/index.php?title=Singleton_pattern

Sorry for adding to the noise.











I've been trying to come up with a clean and computationally efficient way to declare a set of state variables that can be accessed by multiple threads. I'm sure that there are good and bad ways to handle this, and I've found much debate on the web regarding different approaches. I've got a way now that seems to work, but I wanted to vet it against the experts herein to see if I'm possibly missing something.

My approach (certainly not unique) is to use a class made up of static variables and static getter/setter functions that utilize a mutex. See my example code below:




#ifndef SYSSTATE_H
#define SYSSTATE_H

#include <QMutex>

class SysState
{
private:

// Mutex
static QMutex mutex;

// State Variables
static double stateVar1;

public:

static void Init()
{
// this function must be called ONCE (and only once) to initialize the mutex
mutex = new QMutex();
}

static void Deinit()
{
// this function must be called to prevent a memory leak
delete mutex;
}

/////////////////////////////////////////////////////////////////
static double GetStateVar1()
{
mutex.lock();
double val = stateVar1;
mutex.unlock();
return val;
}

static void SetStateVar1(double val)
{
mutex.lock();
stateVar1 = val;
mutex.unlock();
}
};

double SysState::stateVar1;

#endif // SYSSTATE_H




Each thread should include this header file ("sysstate.h"). No explicit instance of SysState is created (it's static).
The syntax for use inside each thread is:

double val1 = SysState::GetStateVar1();

SysState::SetStateVar1(123.45);

One, and only one, thread should call the COTMstate::Init() function...probably in my GUI thread that sets up all the other threads. This function initializes the class's QMutex object. It should also call the COTMstate::Deinit() function to clean up the QMutex.


This seems to work cleanly, but I wasn't sure if I am misusing the QMutex, or if there are situations that I need to be aware of, or if there are any suggested improvements.

I'm new to the concept of sharing data in this way, but am in need of a computationally efficient way to share state between many threads.

Thanks,

Bryan

Lesiok
28th April 2012, 09:27
Are You sure that this code is compilable ?

amleto
28th April 2012, 13:03
it wont.

Mutex mutex;
mutex = new Mutex;

will not compile.


op should remove Init and Deinit methods

Cruz
29th April 2012, 21:00
What's the advantage of using the singleton pattern over the suggested static object?

stampede
29th April 2012, 21:08
Are You sure that this code is compilable ?
It looks kinda like Java code.