注册 登录
编程论坛 Python论坛

Python 多线程 锁 问题

FishK 发布于 2019-01-04 10:02, 1580 次点击
程序代码:

import threading

VALUE = 0
gLOCK = threading.Lock()


class MyThread(threading.Thread):

    def __init__(self, loop_times):
        super().__init__()
        self.loop_times = loop_times

    def run(self):
        global VALUE
        for i in range(self.loop_times):
            gLOCK.acquire()
            VALUE += 1
            gLOCK.release()

        print(self.loop_times, self.name, VALUE)


if __name__ == '__main__':
    for i in range(2):
        MyThread(1000000).start()

我想知道为什么这样使用锁得不到期望的预期结果:
1000000 Thread-1 1000000
1000000 Thread-2 2000000
1 回复
#2
eakit672019-01-07 22:12
        for i in range(self.loop_times):
            gLOCK.acquire()    #当执行 VALUE += 1的时候锁住
            VALUE += 1
            gLOCK.release()    #执行完 VALUE += 1的时候解锁

你把锁放在循环中,所以两个线程是在交替进行 VALUE += 1 。

代码改成以下,就变成一个线程先执行完循环,再到另一个线程执行循环。
gLOCK.acquire()
for i in range(self.loop_times):
            VALUE += 1
gLOCK.release()
1