[Tutor] thread locks

dman dsh8290@rit.edu
Mon, 3 Dec 2001 20:28:28 -0500


On Mon, Dec 03, 2001 at 04:39:38PM -0500, Rick Pasotto wrote:
| If the first thing I do in a long running function is to acquire a
| lock, can I be guaranteed that the first statement after lauching
| that function as a thread can accurately check for the existence
| of the lock?

You are not guaranteed that the thread will actually run as soon as it
is started.

| include thread,time
| mutex = thread.allocate_lock()
| def func():
| 	mutex.acquire()
| 	# do lots of stuff
| 	mutex.release()
| 
| thread.start_new(func,())
| while 1:
| 	if mutex.locked():
| 		time.sleep(1)
| 	else:
| 		break
| # thread has finished so I can do other things

| Or is there a better way to solve my problem?

import threading , time
def func() :
    while 1 : pass # do something that takes a while

t = threading.Thread( target=func )
t.start()
while t.isAlive() : time.sleep( 1 )

| I know this seems to defeat the purpose of using a thread but this is
| in a Tkinter program and if I don't do this the main window will not
| get redrawn if the user covers it up, etc.

Depending on how this is used and what it affects, you could just
start the thread and let it go.  Sometimes there is no need to make
the user wait until it is done.

BTW, you are aware that Tk is not thread-safe, right?  It is only safe
to modify any widgets in the Tk main thread.  If you aren't careful
with this, you can have spurious lockups and other bad things happen.
I don't know about Tk, but Swing has a method that takes a Runnable
object and queues it at the end of the event queue so that it is run
in the Swing main thread.  The runnable object would only contain the
code to update the GUI, not the labor stuff.

-D

-- 

Come to me, all you who are weary and burdened, and I will give you
rest.  Take my yoke upon you and learn from me, for I am gentle and
humble in heart, and you will find rest for your souls.  For my yoke
is easy and my burden is light.
        Matthew 11:28-30