Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
A lock that prioritizes acquire()s?
There are currently too many topics in this group that display first. To make this topic appear first, remove this option from another topic.
There was an error processing your request. Please try again.
flag
  3 messages - Collapse all  -  Translate all to Translated (View all originals)
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
MRAB  
View profile  
 More options Oct 24 2012, 3:41 pm
Newsgroups: comp.lang.python
From: MRAB <pyt...@mrabarnett.plus.com>
Date: Wed, 24 Oct 2012 20:41:37 +0100
Local: Wed, Oct 24 2012 3:41 pm
Subject: Re: A lock that prioritizes acquire()s?
On 2012-10-24 19:54, David M Chess wrote:

Here's my take on it:

class PriorityLock(object):

     def __init__(self):
         self._lock = threading.Lock()
         self._waiter_queue = []
         self._queue_lock = threading.Lock()

     def acquire(self, importance=0):
         this_thread = threading.currentThread()

         # Add this thread to the queue
         with self._queue_lock:
             self._waiter_queue.append((importance, this_thread))
             self._waiter_queue.sort(reverse=True, key=lambda pair:
pair[0]) # Move the most important to the start.

         # Acquire and retain the lock when this thread is at the start
of the queue.
         while True:
             self._lock.acquire()

             with self._queue_lock:
                 if self._waiter_queue[0][1] == this_thread: # We win.
                     del self._waiter_queue[0] # Not waiting anymore.
                     return # Return with lock acquired.

             self._lock.release() # We are not most important: release
and retry.
             time.sleep(0.01) # Give the other threads a chance.

     def release(self):
         self._lock.release()


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Ian Kelly  
View profile  
 More options Oct 24 2012, 4:20 pm
Newsgroups: comp.lang.python
From: Ian Kelly <ian.g.ke...@gmail.com>
Date: Wed, 24 Oct 2012 14:19:28 -0600
Local: Wed, Oct 24 2012 4:19 pm
Subject: Re: A lock that prioritizes acquire()s?
On Wed, Oct 24, 2012 at 12:54 PM, David M Chess <ch...@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


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
Ian Kelly  
View profile  
 More options Oct 24 2012, 5:00 pm
Newsgroups: comp.lang.python
From: Ian Kelly <ian.g.ke...@gmail.com>
Date: Wed, 24 Oct 2012 15:00:09 -0600
Local: Wed, Oct 24 2012 5:00 pm
Subject: Re: A lock that prioritizes acquire()s?

On Wed, Oct 24, 2012 at 2:19 PM, Ian Kelly <ian.g.ke...@gmail.com> wrote:
> I used a PriorityQueue and Conditions to get rid of the ugly while True loop.

Same things, but with Events instead of Conditions.  This is just a
bit more readable.

The PriorityQueue is also probably unnecessary, since it's always
accessed with the mutex held.  A heapq would be fine.

import threading
import Queue

class PriorityLock(object):

    def __init__(self):
        self._is_available = True
        self._mutex = threading.Lock()
        self._waiter_queue = 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
        event = threading.Event()
        self._waiter_queue.put((priority, event))
        self._mutex.release()
        event.wait()
        # When the event is triggered, we have the lock.
        return True

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


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.
End of messages
« Back to Discussions « Newer topic     Older topic »