使用线程在后台持续运行 运行?

Function constantly running in the background using threading?

我想让下面的函数运行不断地循环来模拟股票的随机变动,同时用户可以使用菜单,这意味着它必须在后台运行。 我试图通过使用线程来做到这一点,但我就是无法让它工作。 我正在使用股票模拟器的代码,但不知道这是否相关。

def stockPriceRandomiser(stockPrices):

    length = len(stockPrices)
    count = 0
    while count < length:

        ranNum = randint(0, 1)

        if ranNum == 0:
            loss = randint(90, 99)/100

            stockPrices[count] = stockPrices[count]*loss



        elif ranNum == 1:
            profit = randint(101, 110)/100

            stockPrices[count] = stockPrices[count]*profit

        count = count + 1
    time.sleep(20)
    return stockPrices

stockPrices = [79, 45, 1233, 67, 54, 5000, 7000, 6974]

你的线程应该在一个循环中休眠,而不是在它终止之前。 当设置或重置从主线程控制的标志时,它应该离开循环。这是一个例子:

# 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.S。该代码用于 Python 2