进程(Process)是计算机程序中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。
#!/usr/bin/python3
# Learning note from Runoob(https://www.runoob.com/python3/python3-multithreading.html)
import threading
import queue # Use model Queue, the priority queue
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print("Start thread " + self.name)
process_data(self.name, self.q)
print("Exit thread " + self.name)
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print("%s processing %s" % (threadName, data))
else:
queueLock.release()
time.sleep(1)
threadList = ["thread-1", "thread-2", "thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for threadName in threadList:
thread = myThread(threadID, threadName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for data in nameList:
workQueue.put(data)
queueLock.release()
# Wait, until the queue is empty
while not workQueue.empty():
pass
# Notify the thread to exit at the right time
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print("Exit main thread")