研究多线程,我写了一个小代码,理论上应该是依次启动线程,写了这么一个小脚本:
import queue
import threading
exit_flag = False
class MyThread(threading.Thread):
def __init__(self, thread_id, name, q):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.q = q
def run(self):
print("Starting {}".format(self.name))
process_data(self.name, self.q)
print("Exiting {}".format(self.name))
def process_data(working_thread, q):
while not exit_flag:
queue_lock.acquire()
if not work_queue.empty():
data = q.get()
queue_lock.release()
print("{} processing {}".format(working_thread, data))
thread_list = ["Thread-1", "Thread-2", "Thread-3"]
name_list = ["One", "Two", "Three", "Four", "Five"]
queue_lock = threading.Lock()
work_queue = queue.Queue(10)
threads = []
t_id = 1
for t_name in thread_list:
thread = MyThread(t_id, t_name, work_queue)
thread.start()
threads.append(thread)
t_id += 1
queue_lock.acquire()
for word in name_list:
work_queue.put(word)
queue_lock.release()
while not work_queue.empty():
pass
exit_flag = True
for t in threads:
t.join()
print("Main thread end!")
最有趣的是,在调试模式下工作时,一切正常,但如果你只是让它运行,那么什么都不会发生,只有线程正在运行的消息。你能告诉我哪里出错了吗?
出去
根据接受的答案,您想启动
3
一个线程并处理5
其中的单词:线程池本身内部使用了一个队列,提供了一个简单的接口。
与其阻塞,
threading.Lock()
不如使用以下可能性Queue
:文档:https ://docs.python.org/3.6/library/queue.html
还有例子