我有一个线程列表。以下代码使用'with'语句释放块末尾的互斥锁。这非常有用,因为它允许用户循环遍历每个线程并选择停止它或使其保持运行。
import threading
#subclass with state
class Mythread(threading.Thread):
def __init__(self,myId, astr, mutex):
self.myId = myId
self.astr = astr
self.mutex = mutex
threading.Thread.__init__(self)
def run(self):
while True:
with self.mutex:
print('[%s] => %s' % (self.myId, self.astr))
ans=raw_input("Enter s to stop thread...")
if ans == 's':
break
stdoutmutex = threading.Lock()
threads = []
for i,j in zip(range(7),['A', 'B', 'C','D','E','F','G']):
thread = Mythread(i,j,stdoutmutex)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
为了确保线程按照'threads'列表中的顺序循环,我使用了Queue模块来控制线程锁的顺序:
thread = q.get()
with thread.mutex:
修改过的脚本:
import threading, Queue
#subclass with state
class Mythread(threading.Thread):
def __init__(self,myId, astr, mutex):
self.myId = myId
self.astr = astr
self.mutex = mutex
threading.Thread.__init__(self)
def run(self):
while True:
thread = q.get()
with thread.mutex:
print('[%s] => %s' % (self.myId, self.astr))
ans=raw_input("Enter s to stop thread...")
if ans == 's':
q.task_done()
break
else:
q.put(thread)
stdoutmutex = threading.Lock()
threads = []
q = Queue.Queue()
for i,j in zip(range(7),['A', 'B', 'C','D','E','F','G']):
thread = Mythread(i,j,stdoutmutex)
threads.append(thread)
for thread in threads:
q.put(thread)
thread.start()
for thread in threads:
thread.join()
这似乎与正确的线程顺序A,B,C ...一起发送到标准输出。但是,是否可以验证队列是否有效并且这不仅仅是巧合?