Python的线程和多进程锁不起作用

时间:2017-11-14 13:43:53

标签: python multithreading synchronization locking

我有一个演示多线程和锁定的玩具示例。没有锁,我显然对全局counter变量有不好的价值。但是,当我输入threading.Lock时,会导致更多的不一致。此外,multiprocessing.Lock()也没有完全解决问题。

import threading 
from multiprocessing import Process, Lock

num_experiments = 200
num_threads = 5 
iterations_in_one_thread = 500 

def f(): 

    global counter 
    for i in range(iterations_in_one_thread): 
        with lock: 
            counter += 1 

bad_count = 0 
# lock = threading.Lock()
lock = Lock() 

for x in range(num_experiments): 

    counter = 0 
    threads = [] 
    for i in range(num_threads):
        t = threading.Thread(target=f)
        threads.append(t)
        t.start()

    for i in threads: 
        t.join() 

    if counter != num_threads * iterations_in_one_thread: 
        bad_count += 1 
        print counter 


print "Bad count:", bad_count
print "Total runs:", num_experiments 

我期望的输出:Bad count: 0 输出我得到:Bad count: 3(有时高达6)

我在python 2.7.3上

Python 2.7.13 |Anaconda custom (x86_64)| (default, Dec 20 2016, 23:05:08)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin

1 个答案:

答案 0 :(得分:1)

我认为你刚刚做了一个简单的拼写错误。

for i in threads: 
    t.join()

应该是

for i in threads: 
    i.join()

否则,您只加入最后一个帖子。此外,您可能不应该将多处理库与线程库混合使用。坚持threading.Lock