Greetings wise brothers.

I am working on a multi threaded perl script (using a Thread_pool design pattern), where I have one thread building a queue of work to be done, and a number of worker threads pulling items of work from the queue.

In order to keep the queue size sensible, and the workers fully employed, I am using a Thread::Semaphore to control the work finding thread. If the queue becomes full then the work finding thread calls down() on the semaphore to block untill it is signaled to resume. If a worker thread finds the queue to be less than half full it calls up() on the semaphore to wake up the work finding thread to keep the queue of work full.

My problem is that Thread::Semaphore stores an integer (equal to the number of up() calls less the number of down() calls), and not a boolean value. I have a large number or worker threads and they can make lots of up() calls driving the value in the semaphore to a large number, so that it takes a lot of down() calls before the semaphore blocks.

What I would like is a semaphore that contains a boolean 1 or 0 value, so that any number of up() calls will not increase the value beyond 1, and every call to down() will always block untill another thread calls up.

Is there a way of using Thread::Semaphore in this way, or an alternative semaphore module that can be used for this purpose?


In reply to Boolean Thread::Semaphore ? by chrestomanci

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.