PDA

View Full Version : QSempahore max reourse



matteo.ceruti
12th June 2012, 16:24
Hi, is it possible to create a QSemaphore that can acquire a max number of resourse?
For example if max is 1:
sem.available() == 1
sem.release()
sem.available() == 1
sem.acquire()
sem.available() == 0
sem.release()
sem.available() == 1
sem.release()
sem.available() == 1
thanks
Teo

wysota
13th June 2012, 22:53
I think you should explain better what you mean.

ChrisW67
14th June 2012, 06:19
I think the OP wants a QSemaphore that will not allow QSemaphore::release() to increase the number of resources available beyond the initial allocation at construction. It is not possible to adapt QSemaphore for this (it does not remember the original allocation, just the current number) but it should be easy enough to wrap one to enforce this. I am not sure this is useful unless you are trying to cover for poor programming elsewhere. Perhaps the OP will explain further.

wysota
14th June 2012, 09:40
I don't see how this would be useful. If you can discard a V operation on a semaphore then what's the point of using that semaphore... Maybe using QMutex with QWaitCondition and a regular int variable would be better...

matteo.ceruti
14th June 2012, 11:17
Yes, ChrisW67 the problem is correct, but I can't use QMutex or QWaitCondition, because they have not memory
t0 -> waitCondition.wakeone


t4 -> waitCondtion.wait -> block the thread.

Instead I need
t0 -> semaphore.relase


t4 -> semaphore.acquire -> not block the thread.

Suggestions?

wysota
14th June 2012, 11:21
QMutex m;
QWaitCondition c;
int val = 1;

m.lock();
while(val == 0) c.wait(&m);
val--;
m.unlock();

// ...

m.lock();
if(val < max)
val++;
c.wakeAll();
m.unlock();
Still, I have no idea what's the point of having such a construction.

kuroi_neko
14th June 2012, 14:37
If the semaphore producer already knows the consumer will have to wakeup 5 times, why not tell the consumer and let it handle the repetition while using a vanilla semaphore for synchronization?

Creating freak synch objects is a recipe for disaster, if you want my opinion. Asynchronous programming is intrinsically full of pitfalls, no need to dig your own on top of it.

The need for weird sync objects usually comes from weird design. In this example, I really doubt you could describe the producer-consumer semantics of your freak semaphore in plain, understandable english.

Looks more like the "if task1 does this and it's the right moment, then I will poke task2 with a stick until it wakes up" approach. These behaviours should remain at application level, they don't belong in low-level synch objects.

iamtechie.ami
9th January 2013, 16:59
You might check the video to get basic understanding of the semaphore

https://www.youtube.com/watch?v=VQFJQJGmixM