[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

class ThreadCounter:
def init(self):
self.count = 0
self.mutex = thread.allocate_lock() # or use Threading.semaphore
def incr(self):
self.mutex.acquire() # or with self.mutex:
self.count += 1
self.mutex.release()
def decr(self):
self.mutex.acquire()
self.count -= 1
self.mutex.release()
def len(self): return self.count # True/False if used as a flag


#################################################################################


self-test code: split thread action into main, exits, progress


#################################################################################


if name == 'main': # self-test code when run
import time # or PP4E.Gui.Tour.scrolledtext
from tkinter.scrolledtext import ScrolledText


def onEvent(i): # code that spawns thread
myname = 'thread-%s' % i
startThread(
action = threadaction,
args = (i, 3),
context = (myname,),
onExit = threadexit,
onFail = threadfail,
onProgress = threadprogress)


thread's main action


def threadaction(id, reps, progress): # what the thread does
for i in range(reps):
time.sleep(1)
if progress: progress(i) # progress callback: queued
if id % 2 == 1: raise Exception # odd numbered: fail


thread exit/progress callbacks: dispatched off queue in main thread


def threadexit(myname):
text.insert('end', '%s\texit\n' % myname)
text.see('end')


def threadfail(exc_info, myname):
text.insert('end', '%s\tfail\t%s\n' % (myname, exc_info[0]))
text.see('end')


def threadprogress(count, myname):
text.insert('end', '%s\tprog\t%s\n' % (myname, count))
text.see('end')
text.update() # works here: run in main thread


make enclosing GUI and start timer loop in main thread


GUIs, Threads, and Queues | 643
Free download pdf