线程内部的python全局变量

时间:2017-02-06 19:58:31

标签: python multithreading variables locking global

故事以两个线程开始,一个全局变量改变了很多时间:)

第一个线程(为简单起见,我们将调用t1)生成一个随机数并将其存储在全局变量GLB中。

第二个线程(也称为t2)检查全局变量的值,当它达到一个值时,开始打印它的值直到一段时间。

但是如果t1改变了那个全局变量的值,也改变了循环中的值,我不想要这个!

我尝试编写伪代码:

import random
import time
import threading


GLB = [0,0]

#this is a thread 
def t1():
    while True:
        GLB[0] = random.randint(0, 100)
        GLB[1] = 1
        print GLB
        time.sleep(5)


#this is a thread 
def t2():
    while True:
        if GLB[0]<=30:
            static = GLB
            for i in range(50):
                print i," ",static
                time.sleep(1)




a = threading.Thread(target=t1)
a.start()


b = threading.Thread(target=t2)
b.start()

while True:
    time.sleep(1)

问题是:为什么循环内部的变量静态变化?它应该保持恒定unitl它从循环中逃脱! 我可以创建一个锁变量吗?或者还有其他方法可以解决问题吗?

谢谢你的问候。

1 个答案:

答案 0 :(得分:0)

GLB是一个可变对象。要让一个线程在另一个线程修改它时看到一致的值,您可以使用锁定临时保护对象(修改器将等待)或复制对象。在您的示例中,副本似乎是最佳选择。在python中,切片副本是原子的,因此不需要任何其他锁定。

import random
import time
import threading

GLB = [0,0]

#this is a thread 
def t1():
    while True:
        GLB[0] = random.randint(0, 100)
        GLB[1] = 1
        print GLB
        time.sleep(5)

#this is a thread 
def t2():
    while True:
        static = GLB[:]
        if static[0]<=30:
            for i in range(50):
                print i," ",static
                time.sleep(1)

a = threading.Thread(target=t1)
a.start()

b = threading.Thread(target=t2)
b.start()

while True:
    time.sleep(1)