Critical sections and mutexes

David Brady daves_spam_dodging_account at yahoo.com
Tue Oct 23 21:06:59 CEST 2001


Firstoff, Shouldn't the plural of "mutex" be
"mutices"?  :-)

I am trying to write a multithreaded app in Python on
Win32.  These threads need to communicate with one
another, so they can collaborate.  Right now, there is
a common resource in the main thread that each child
needs to interact with, and there are resources in
each child thread that the main thread will interact
with.

I've read through the thread and threading
documentation as well as the sample code in Appendix D
of Python Programming on Win32.  I can make threads
start, run and stop.  But the "lock object" code is
baffling me outright.  Do I create a lock inside the
child thread, or do I create it wherever and attach it
to a thread?  What I'm wondering is:

- How can I lock a resource owned by a child thread
from the main application, diddle with it, and unlock
it?
- How can I lock a resource owned by the main thread
from a child thread, diddle with it, and unlock it?
- Each lock/diddle/unlock operation is designed to
keep the resource locked for as little time as
possible, but I can still imagine the thread being
preempted in the middle of an update.  Do I need a
critical section?  If so, how do I implement one?  The
only case I can see this being a problem is when, say,
Thread A locks something in the main thread, starts to
interact with it, is preempted, and then the main
thread gets a timeslice and interacts with the locked
resource--which it views as local and doesn't need to
check for a lock.

Can that last situation even exist?  Do I need to
create a third, "go-between" object so that both
threads have to go through the lock/unlock process to
get at the resource?

Here's a rough cut at what I'm sort of thinking:

main_Q = PriorityQueue() # queueing class

class ServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.Q = PriorityQueue()

    def run(self):
        # if messages waiting on socket:
            # get messages into self.Q
        # if self.Q has messages:
            # if can acquire lock on main_Q:
                # move msgs from self.Q to main_Q
                # release lock on main_Q

# main thread:
while 1:
    # if main_Q has messages:
        # dispatch them


Thank you,

-dB

=====
--
David Brady
daves_spam_dodging_account at yahoo.com
I'm feeling very surreal today... or *AM* I?

__________________________________________________
Do You Yahoo!?
Make a great connection at Yahoo! Personals.
http://personals.yahoo.com




More information about the Python-list mailing list