Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32065

Re: A lock that prioritizes acquire()s?

Path csiph.com!usenet.pasdenom.info!weretis.net!feeder1.news.weretis.net!feeder.erje.net!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!news2.euro.net!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <ian.g.kelly@gmail.com>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'else:': 0.03; 'retrieved': 0.05; '"__main__":': 0.07; '__name__': 0.07; 'try:': 0.07; 'ugly': 0.07; 'any.': 0.09; 'loop.': 0.09; 'skip:[ 30': 0.09; 'subject:()': 0.09; 'def': 0.10; 'thread': 0.11; '24,': 0.16; 'oct': 0.16; 'subject:lock': 0.16; 'test()': 0.16; 'test():': 0.16; 'threading': 0.16; 'threads': 0.16; 'threads:': 0.16; 'zero,': 0.16; 'wed,': 0.16; 'wrote:': 0.17; 'bit': 0.21; 'import': 0.21; 'cheers,': 0.23; 'second': 0.24; 'header:In-Reply- To:1': 0.25; 'values': 0.26; 'first,': 0.27; 'order.': 0.27; 'first.': 0.27; 'thoughts': 0.27; 'message-id:@mail.gmail.com': 0.27; 'went': 0.28; 'priority': 0.29; 'queue': 0.29; 'second,': 0.29; 'skip:_ 10': 0.29; 'class': 0.29; 'received:209.85.215.46': 0.30; 'seconds': 0.30; 'running': 0.32; 'skip:s 30': 0.33; 'rid': 0.33; 'to:addr:python-list': 0.33; 'received:google.com': 0.34; 'false': 0.35; 'pm,': 0.35; 'subject:?': 0.35; 'received:209.85': 0.35; 'there': 0.35; 'next': 0.35; 'except': 0.36; 'but': 0.36; 'too': 0.36; 'skip:p 20': 0.36; 'two': 0.37; 'being': 0.37; 'received:209': 0.37; 'subject:: ': 0.38; 'skip:l 20': 0.38; 'to:addr:python.org': 0.39; 'header:Received:5': 0.40; 'most': 0.61; 'lower': 0.61; 'first': 0.61; 'maximum': 0.63; 'importance.': 0.84; 'random,': 0.84; 'to:name:python': 0.84; 'virtue': 0.84; 'average': 0.93
DKIM-Signature v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :content-type; bh=WQ0B0yxpPNoxCftLNTpIscNsp4ZUdqmJXDTy/SdrgZ8=; b=sRuH508GbibZGejKWfMPZc8yG4kiE+kGIkiQsa/SQyJzEnLsM/5V6AY/QSVe9iwmtS g3nFItUf64tE9V1HKDfNBc07ycZP3jCZc9dQaMMYausJgo4lT5Q1I/VwEzBSMgv1bAif I43myHkglQBimqk6JGCpjTZQTtDZe2q4UgoY0ngkxQV/ufUhxFWu6j4D0xmSlYMEXoNn kjHzKTutWW0ESp/IIAImSWQ8qXFguYsuTb2saHaiOfnu/c8f3mrO6VwAj41TLIwvqZpd CFMo273yhzmnS2OimzABlnySUY6rf4+g2DlyO2jJOrr6ZdMhnqItqGrXjCovwZXh0ay0 Qjmg==
MIME-Version 1.0
In-Reply-To <OFB845143C.E36D6F51-ON85257AA1.0066C7C0-85257AA1.0067DD35@us.ibm.com>
References <OFB845143C.E36D6F51-ON85257AA1.0066C7C0-85257AA1.0067DD35@us.ibm.com>
From Ian Kelly <ian.g.kelly@gmail.com>
Date Wed, 24 Oct 2012 14:19:28 -0600
Subject Re: A lock that prioritizes acquire()s?
To Python <python-list@python.org>
Content-Type text/plain; charset=ISO-8859-1
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.2794.1351110001.27098.python-list@python.org> (permalink)
Lines 88
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1351110001 news.xs4all.nl 6983 [2001:888:2000:d::a6]:56667
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:32065

Show key headers only | View raw


On Wed, Oct 24, 2012 at 12:54 PM, David M Chess <chess@us.ibm.com> wrote:
> Seeking any thoughts on other/better ways to do this, or whether the
> inefficiency will be too eyerolling if we get say one request per second
> with an average service time a bit under a second but maximum service time
> well over a second, and most of them are importance zero, but every (many)
> seconds there will be one or two with higher importance.

I used a PriorityQueue and Conditions to get rid of the ugly while True loop.


import threading
from Queue import PriorityQueue, Empty

class PriorityLock(object):

    def __init__(self):
        self._is_available = True
        self._mutex = threading.Lock()
        self._waiter_queue = PriorityQueue()

    def acquire(self, priority=0):
        self._mutex.acquire()
        # First, just check the lock.
        if self._is_available:
            self._is_available = False
            self._mutex.release()
            return True
        condition = threading.Condition()
        condition.acquire()
        self._waiter_queue.put((priority, condition))
        self._mutex.release()
        condition.wait()
        condition.release()
        return True

    def release(self):
        self._mutex.acquire()
        # Notify the next thread in line, if any.
        try:
            _, condition = self._waiter_queue.get_nowait()
        except Empty:
            self._is_available = True
        else:
            condition.acquire()
            condition.notify()
            condition.release()
        self._mutex.release()

def test():
    import random, time

    def thread(lock, priority):
        lock.acquire(priority)
        print("Thread %d running" % priority)
        time.sleep(1)
        lock.release()
    lock = PriorityLock()
    threads = [threading.Thread(target=thread, args=(lock, x)) for x
in range(10)]
    random.shuffle(threads)
    for thread in threads:
        thread.start()
    for thread in threads:
        thread.join()

if __name__ == "__main__":
    test()


Output:

Thread 9 running
Thread 0 running
Thread 1 running
Thread 2 running
Thread 3 running
Thread 4 running
Thread 5 running
Thread 6 running
Thread 7 running
Thread 8 running

Note that with the PriorityQueue, lower priority values are retrieved
first.  Thread 9 ran first just by virtue of being first to the gate,
and after that you can see that everything went in order.

Cheers,
Ian

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: A lock that prioritizes acquire()s? Ian Kelly <ian.g.kelly@gmail.com> - 2012-10-24 14:19 -0600

csiph-web