代码之家  ›  专栏  ›  技术社区  ›  Oliver Frost

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

  •  0
  • Oliver Frost  · 技术社区  · 8 年前

    我希望以下函数在循环中不断运行,以模拟股票的随机运动,而用户可以使用菜单,这意味着它必须在后台运行。 我曾尝试使用线程来实现这一点,但我就是无法让它工作。 我正在使用股票模拟器的代码,但不知道这是否相关。

    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]
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Dmytro Y.    8 年前

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

    # 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的