PDA

View Full Version : static QMutex



mhoover
20th August 2009, 04:32
For some reason when I declare a public or private static QMutex in a class header file and try to use it in the source file, I get to the linking phase and then it barfs.


sclient.o: In function `SClient::setHostName(QString const&)':
/home/rhoover/sclient.cpp:176: undefined reference to `SClient::mutex'
/home/rhoover/sclient.cpp:180: undefined reference to `SClient::mutex'
collect2: ld returned 1 exit status
make: *** [aodsc] Error 1

When I declared it plain as day:


class SClient : public QObject
{
Q_OBJECT
public:
SClient(QObject *parent = 0);
SClient( QObject *parent, const QString & _host, bool _parsing );
~SClient();
static QMutex mutex;
...
}

mhoover
20th August 2009, 04:36
You know what's crazy is it builds fine if I leave off the "static". It just doesn't work.

mhoover
20th August 2009, 04:43
So I moved the "static mutex" declaration to a global variable in my thread source file and it works.


locked.
Opening config file.
about to unlock
unlocked.
setHostName() succeeded.
locked.
Opening config file.
about to unlock
unlocked.
setHostName() succeeded.
locked.
Opening config file.
about to unlock
unlocked.
setHostName() succeeded.
locked.
Opening config file.
about to unlock
unlocked.

But I hear global variables don't mix with threading.

Opinions? Suggestions? Threats? ;)

nish
20th August 2009, 05:21
for static variable you have to define them in cpp file..

/
//.h file
class someclass
{
public:
someclass();
static QMutex mutex;//declare it
}

//.cpp file
QMutex someclass::mutex; //define it.

someclass::someclass()
{

}

franz
20th August 2009, 08:12
Why do you want to declare it static? Static makes it available to the containing file only, effectively making it private for your class. What's wrong with just declaring it private?

lyuts
20th August 2009, 10:01
... Static makes it available to the containing file only...
It is true for C.

I think he wants to make it shared among several instances of SClient.

mhoover: Where do you define your mutex?

mhoover
21st August 2009, 00:48
Thanks again, Mr. Death. Using static variables is elementary, so i perhaps I am a newb after ;)

Lyuts, I defined it as a global variable in my .cpp and that works. I will change it to use Mr. Death's approach as that feels safer.

Franz, the QMutex can't lock between threads unless it has scope access to the different threads. To make sure they can all see the same mutex, I defined it as static. Hope that explains it.

Thanks, everyone!

formula
8th August 2014, 06:39
thank you, Mr. Nish.