线程应该在循环中休眠,而不是在它终止之前。
当设置或重置主线程控制的标志时,它应该离开循环。以下是一个示例:
# coding=utf-8
"""
> python stock.py
Press Ctrl+C to exit
[86, 52, 1197, 63, 62, 5165, 6481, 7338]
[86, 52, 1197, 63, 62, 5165, 6481, 7338]
[86, 52, 1197, 63, 62, 5165, 6481, 7338]
[101, 55, 1035, 66, 62, 4457, 7172, 6673]
[101, 55, 1035, 66, 62, 4457, 7172, 6673]
^CTerminating...
"""
from random import random
from threading import Thread
from time import sleep
import signal
def stock_price_randomiser(shared_data):
while shared_data.threads_active:
prices = shared_data.stock_prices
for i in xrange(len(prices)):
coeff = 0.8 + random() * 0.4 # from 0.8 to 1.2
prices[i] = int(prices[i] * coeff)
sleep(5)
class SharedData(object):
"""Represent an object that is shared between threads"""
stock_prices = [79, 45, 1233, 67, 54, 5000, 7000, 6974]
# As soon as this flag turns False all threads should gracefully exit.
threads_active = True
def main():
shared_data = SharedData()
randomiser_thread = Thread(target=stock_price_randomiser,
args=(shared_data,))
def handle_sigint(signal, frame):
print "Terminating..."
# We don't want to forcibly kill the thread, so we ask it
# to exit cooperatively.
shared_data.threads_active = False
signal.signal(signal.SIGINT, handle_sigint)
print "Press Ctrl+C to exit"
# Start the thread
randomiser_thread.start()
while shared_data.threads_active:
print shared_data.stock_prices
sleep(2)
# Wait for the thread exit
randomiser_thread.join()
if __name__ == "__main__":
main()
我们启动一个线程并传递一个共享的对象。该对象包含
stock_prices
列表和一个用于告诉两个线程何时退出的标志。一个线程更新列表,另一个线程读取列表以显示它。当用户按下Ctrl+C时,我们通过重置标志来处理中断信号,使线程在下一次循环迭代中退出。
P、 代码是针对Python 2的