为什么在python中使用线程时全局变量不会增加?

时间:2014-10-08 12:57:47

标签: python multithreading

对于我的代码,pytest_status ['finished']变量以非常有趣的方式递增。有时我可以看到'2'或'3'(我希望每次run_test函数调用都有增量):

test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 1/53: success
test 2/53: success
test 1/53: success
test 1/53: success

等等。我特意将它移出锁定,我的代码:

import subprocess
from multiprocessing import Pool, Lock

pytest_status = {
    'finished' : 0,
    'total'    : 0
}

print_lock = Lock()

def run_test(test):
    status = subprocess.call(...)

    global pytest_status
    pytest_status['finished'] += 1

    print_lock.acquire()
    print 'test ' + str(pytest_status['finished']) + '/' + str(pytest_status['total']) + ': ' + ('success' if status == 0 else 'failure')    
    print_lock.release()

def main():
    params = [...]

    global pytest_status    
    pytest_status['total'] = len(params)

    print 'will perform ' + str(pytest_status['total']) + ' tests'

    pool = Pool(30)
    pool.map(run_test, params)
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:3)

你没有使用线程。您正在使用流程。根据定义,它们具有所有数据的单独副本。你获得2或3的唯一一次是当同一个过程碰巧运行多个工作时。

答案 1 :(得分:1)

如果要在进程之间传输数据,可以使用Pipe或Query。