简体   繁体   English

锁定python的行为与预期不符

[英]Locking in python does not behave like expected

I have this code: 我有以下代码:

SP500 = pd.read_csv("http://trading.chrisconlan.com/SPstocks_current.csv", header=-1, names=['Symbol']).copy()
SP500=list(SP500.Symbol)
SP500=['AVGO', 'GM', 'FDX', 'goog']

threads = []
lock = threading.Lock()
offset = 1
multiply = 1
num_of_threads = 4
for i in range(0, num_of_threads):
    t = threading.Thread(target=digest_distros, args=(SP500, i * multiply, i * multiply + offset))
    t.start()
    threads.append(t)
for t in threads:
    t.join()

This is the func 这是功能

def digest_distros(SPT500, start, finish):
    for stock in SP500[start:finish]:

        daily, stock_distro = get_daily_adjusted(stock)
        if daily is None:
            continue
        monthly_adjusted_close=get_monthly_adjusted(stock)
        if monthly_adjusted_close is None:
            continue

        with lock:
            print "\n"
            print "##############   " + stock + "   ##############"
            print daily[['low', 'high', 'open', 'adjusted close']].tail(1)
            print "\n"

            curr_monthly_adjusted=monthly_adjusted_close[-1]
            print "##########################"
            print "current monthly adjusted close is: {}".format(curr_monthly_adjusted)
            required_value_for_signal=find_min_signal_value(monthly_adjusted_close)
            print "Required value for signal tommorow is : {}".format(required_value_for_signal)
            print "##########################"

            print "\n"

            spans = [0.3, 0.5, 1, 2,3,5]
            for span in spans:
                mean=stock_distro[span][0]
                std=stock_distro[span][1]
                if abs(curr_monthly_adjusted-required_value_for_signal) < 3:
                    print "Time span is {:.3f} years, daily change mean {:.3f}, daily change std {:.3f}".format(span,mean,std)
                    z_value=calculate_z_value(required_value_for_signal, curr_monthly_adjusted, mean, std)
                    # if z_value>0.3:
                    print "Probability is: {:.3f}".format(z_value)

When running, if the code reaches the code inside the for loop or inside the if statement (I think), I lose my lock... 运行时,如果代码到达for循环内或if语句内的代码(我认为),我将失去锁...

Can't understand why. 不明白为什么。

Example output for mixed printing. 混合打印的示例输出。

######## GM # ######## GM#

current monthly adjusted close is: 37.64 Required value for signal tommorow is : 38.5 当前每月调整后的收盘价为:37.64信号明暗度的必需值为:38.5

#

Time span is 0.300 years, daily change mean -0.083, daily change std 0.692 Probability is: 0.869 Time span is 0.500 years, daily change mean 0.004, daily change std 0.663 Probability is: 0.904 Time span is 1.000 years, daily change mean 0.009, daily change std 0.531 Probability is: 0.949 时间跨度为0.300年,日变化平均值为-0.083,日变化标准为0.692概率为:0.869时间跨度为0.500年,日变化平均值为0.004,日变化标准为0.663概率为:0.904时间跨度为1.000年,日变化平均值为0.009,每日变化标准0.531概率是:0.949

Time span is 2.000 years, daily change mean 0.018, daily change std 0.512############## AVGO ############## 时间跨度为2.000年,每日变化平均值0.018,每日变化标准0.512 ############## AVGO ###############

Probability is: 0.957 Time span is 3.000 years, daily change mean 0.005, daily change std 0.495 Probability is: 0.960 Time span is 5.000 years, daily change mean 0.011, daily change std 0.477 Probability is: 0.966 概率为:0.957,时间跨度为3.000年,日变化平均值为0.005,日变化标准为0.495概率为:0.960,时间跨度为5.000年,日变化平均值为0.011,日变化标准为0.477,概率为:0.966

The simplest fix to get what you want is to flush the output buffers right before you exit the lock. 获得所需内容的最简单解决方法是在退出锁之前立即刷新输出缓冲区。 Like this: 像这样:

with lock:
    # ... stuff
    print(stuff)
    # etc.
    sys.stdout.flush()

Why is this necessary? 为什么这是必要的? Because print doesn't actually put anything on the terminal. 因为print实际上不会在终端上放任何东西。 What it does is put something in the sys.stdout buffer, so that it will eventually get to the screen. 它所做的是将某些内容放入sys.stdout缓冲区中,以便最终将其显示在屏幕上。 That "eventually" could well be after you've released the lock. “最终”很可能是在您释放锁之后。

Locking works just fine, and there's nothing in your code that isn't locked; 锁定可以很好地工作,并且代码中没有任何东西没有被锁定; the problem is that locking doesn't force every file—or other buffered type—in the universe to become unbuffered. 问题是锁定不会强制Universe中的每个文件或其他缓冲类型变为非缓冲状态。 Think about it this way: if you send data over the network from inside a lock, there's no way to guarantee that the other side has received the data by the time you release the lock (except to wait, still holding the lock, for some acknowledgement). 请这样考虑:如果您是从锁内部通过网络send数据,则无法保证在释放锁时对方已经收到了数据(除了等待,仍然保持锁,对于某些人而言)。确认)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM