[Qt-interest] Using Semaphores multiple times in different instances of a class

Sean Harmer sean.harmer at maps-technology.com
Mon Oct 4 16:27:37 CEST 2010


Hi,

On Monday 04 October 2010 15:10:23 Jannis Achstetter wrote:
> I have an application in C++ that creates multiple instances of a class.
> Every instance shall have its own circular buffer (used to store audio
> samples decoded elsewhere in that instance). An instance of another
> class then calls a function of every decoding-instance to get audio from
> the instance's circular buffer.
> As long there is only one audio stream (one instance of the decoding
> class), everything is fine. As soon as two (ore more) audio streams are
> working with "their" circular buffer, the data gets corrupted.
> To manage the circular buffer, I use QSemaphores as shown in the
> Semaphore Example (Qt Examples -> Threading). Since I do not want them
> global but per-instance, I tried to "declare" the Semaphores in the
> classes header-file as "private" variables. This did not work,
> Semaphores do not behave like normal class instances (the compiler
> throws an error concerning the numeral value in the braces).
> So I declared them in the classes source-code. Since the Semaphores are
> used by several functions of the class, I did not declare them in a
> function itself but outside any function (making them global obiviosly).
> When I try to use the scope ("QSemaphore ClassName::SemName(int)"), the
> compiler throws an error.
> 
> So my question is: How can I implement a class where every instance has
> its own copy of two QSemaphores? Or, if not possible: How do I implement
> a class where every instance has its own circular buffer?
> 
> If anyone wants to see my source code to better understand my problem I
> can host it on my server. Two classes + headers were just too much for a
> mail to a list.

Sounds like a basic C++ problem to me. You cannot initialise an object in the 
class declaration - only declare it. You have to initialise it in the the 
class' constructor. Something like this should do it:

In the header file:

#include <QSemaphore>

class MyClass
{
public:
    MyClass();

    // Other member functions...

private:
    QSemaphore m_sem1;
    QSemaphore m_sem2;
};

In the .cpp file:

MyClass::MyClass()
 : m_sem1( 10 ),
   m_sem2( 0 )
{
}


Does that solve yoru problem?

Sean



More information about the Qt-interest-old mailing list