打印语句在线程代码中混乱-python

时间:2018-09-27 10:50:37

标签: multithreading python-2.7

我有threading的以下(示例)代码可以进行两次计算,从而使整个过程更快:

import time
import numpy as np
import threading

do_threading = 1

def calc_square(numbers):
    print("calculate square numbers")
    for n in numbers:
        time.sleep(0.2)
        print('square', n*n)

def calc_cube(numbers):
    print("calculate cube numbers")
    for n in numbers:
        time.sleep(0.2)
        print('cube', n*n*n)

arr = np.array([2,3,8,9])

if not do_threading:
    t = time.time()    
    calc_square(arr)
    calc_cube(arr)

if do_threading:
    t = time.time()
    t1 = threading.Thread(target = calc_square, args=(arr,))
    t2 = threading.Thread(target = calc_cube, args = (arr,))
    t1.start()
    t2.start()
    t1.join() # wait here until t1 is finished - exectuion joins back into the main programme, main thread
    t2.join()


print("done in: ", time.time() - t)

通常它会按预期输出:

('cube', 8)
('square', 4)
('square', 9)
('cube', 27)
('cube', 512)
('square', 64)
('square', 81)
('cube', 729)
('done in: ', 0.8050000667572021)

但是有时会给出以下信息:

('cube', 8)
('square', 4)
('square', 9)
('cube', 27)
('cube', 512)
('square', 64)
('square'(, 'cube'81, )729
)
('done in: ', 0.8050000667572021)

其中一些括号被弄乱了。

我假设这是因为打印语句在“上一个”打印语句之前由两个单独的线程执行了?

有办法避免这种情况吗?

0 个答案:

没有答案