股票行情有时会陷入僵局

时间:2018-07-15 02:47:22

标签: python multithreading events deadlock

我的Ticker类旨在用于主线程,每当一组已注册的从属线程完成其作业的一次迭代时,其代号就会增加。这似乎工作正常,但有时我会陷入僵局。我上次跑步时,在第451次时陷入僵局。我看不到造成僵局的原因。我正在使用python3.6

#ticker.py

import threading

class Ticker:
    def __init__ (self):
        self.currentTick = 0
        self.functionStatus = {}
        self.uptick = threading.Event()

    def registerFunction (self, funcId):
        self.functionStatus[funcId] = threading.Event()

    # This has to be called only by one master thread
    def createNextTick(self):
        for k, cond in self.functionStatus.items():
            # wake up when each slave thread has finished it share of work
            cond.wait()

        for k, cond in self.functionStatus.items():
            cond.clear()
        self.currentTick += 1
        self.uptick.set()
        self.uptick.clear()
        return self.currentTick

    def isDone (self, funcId):
        self.functionStatus[funcId].set()

    def waitForUptick (self):
        self.uptick.wait()

    def getCurrentTick (self):
        return self.currentTick

    def complete(self):
        for k, cond in self.functionStatus.items():
            cond.set()
        self.uptick.set()



# ticker_test.py
from ticker import *


def laneAccl(numSecs):
    global laneRunning
    funcId = "laneAccl_"+ str (threading.get_ident())
    globTicker.registerFunction(funcId)
    while laneRunning:
        globTicker.isDone (funcId)
        globTicker.waitForUptick()

def sigChange(numSecs):
    global sigRunning
    color = "red"
    funcId = "sigChange_"+ str (threading.get_ident())
    globTicker.registerFunction(funcId)
    while sigRunning:
        for i in range (numSecs):
            globTicker.isDone (funcId)
            globTicker.waitForUptick()
        if color == "red":
            color = "green"
        elif color == "green":
            color = "orange"
        else:
            color = "red"

def startFunctionThreads():
    tArr = []
    for i in range (50):
        for tup in [(laneAccl, 1), (sigChange, 5)]:
            t = threading.Thread (target=tup[0], args=(tup[1], ))
            t.start()
            tArr.append (t)

    return tArr

import time


if __name__ == "__main__":

    laneRunning = True
    sigRunning = True

    globTicker = Ticker()
    tArr = startFunctionThreads ()

    numTicks = 500
    beg = time.time()
    while globTicker.createNextTick() < numTicks:
        pass

    print ("Total time:", time.time() - beg)

    laneRunning = False
    sigRunning = False

    globTicker.complete()

    for t in tArr:
        t.join()

0 个答案:

没有答案