You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importtimedefcountdown(n):
whilen>0:
print('T-minus', n)
n-=1time.sleep(5)
# Create and launch a threadfromthreadingimportThreadt=Thread(target=countdown, args=(10,))
t.start()
使用继承方式
fromthreadingimportThreadclassCountdownTask:
def__init__(self):
self._running=Truedefterminate(self):
self._running=Falsedefrun(self, n):
whileself._runningandn>0:
print('T-minus', n)
n-=1time.sleep(5)
c=CountdownTask()
t=Thread(target=c.run, args=(10,))
t.start()
c.terminate() # Signal terminationt.join() # Wait for actual termination (if needed)
注意使用变量 self._running 退出线程的方式
使用 Queue 进行线程间通信
importQueueimportthreadingimporttimetask_queue=Queue.Queue()
classThreadTest(threading.Thread):
def__init__(self, queue):
threading.Thread.__init__(self)
self.queue=queuedefrun(self):
whileTrue:
msg=self.queue.get()
print(msg)
time.sleep(0.1)
self.queue.task_done()
defmain():
start=time.time()
# populate queue with dataforiinrange(100):
task_queue.put("message")
# spawn a pool of threads, and pass them queue instanceforiinrange(5):
t=ThreadTest(task_queue)
t.setDaemon(True)
t.start()
# wait on the queue until everything has been processedtask_queue.join()
print"Elapsed Time: {}".format(time.time() -start)
if__name__=="__main__":
main()
setDaemon 设置为 True, run 函数中不需要退出,主线程结束后所有子线程退出
如果 setDaemon 设置为 False,则改为
fromqueueimportQueuefromthreadingimportThreadimportcopy# A thread that produces datadefproducer(out_q):
whileTrue:
# Produce some data
...
out_q.put(copy.deepcopy(data))
# A thread that consumes datadefconsumer(in_q):
whileTrue:
# Get some datadata=in_q.get()
# Process the data
...
python 多线程编程
使用回调方式
使用继承方式
注意使用变量
self._running
退出线程的方式使用 Queue 进行线程间通信
setDaemon 设置为 True, run 函数中不需要退出,主线程结束后所有子线程退出
如果 setDaemon 设置为 False,则改为
并且在主函数结束前 join 所有线程
注意
向队列中添加数据项时并不会复制此数据项,线程间通信实际上是在线程间传递对象引用。如果你担心对象的共享状态,那你最好只传递不可修改的数据结构(如:整型、字符串或者元组)或者一个对象的深拷贝。
q.qsize() , q.full() , q.empty() 等实用方法可以获取一个队列的当前大小和状态。但要注意,这些方法都不是线程安全的。可能你对一个队列使用 empty() 判断出这个队列为空,但同时另外一个线程可能已经向这个队列中插入一个数据项。
参考
python3-cookbook Chapter 12 'Concurrency-Starting and Stopping Threads'
Practical threaded programming with Python
The text was updated successfully, but these errors were encountered: