[英]python global variable inside a thread
The story begin with two threads and a global variable that change.. a lot of time :) 故事以两个线程和一个全局变量开始改变..很多时间:)
Thread number one (for simplicity we will call t1) generates a random number and store it in a global variable GLB. 第一个线程(为简单起见,我们将调用t1)生成一个随机数并将其存储在全局变量GLB中。
Thread number two (aka t2) check the value of the global variable and when it reaches a value starts to print his value until a period of time. 第二个线程(也就是t2)检查全局变量的值,当它达到一个值时,开始打印它的值直到一段时间。
BUT if t1 changes the value of that global variable, also change the value inside the loop and I don't want this! 但是如果t1改变了该全局变量的值,也改变了循环内的值,我不想要这个!
I try to write pseudocode: 我尝试写伪代码:
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)
The question is: why variable static change inside the loop for? 问题是:为什么循环内部的变量静态变化? It should be remain constant unitl it escapes from loop! 它应该保持恒定unitl它从循环中逃脱! Could I create a lock to the variable? 我可以创建一个锁变量吗? Or there is any other way to solve the problem? 或者还有其他方法可以解决问题吗?
Thanks regards. 感谢和问候。
GLB
is a mutable object. GLB
是一个可变对象。 To let one thread see a consistent value while another thread modifies it you can either protect the object temporarily with a lock (the modifier will wait) or copy the object. 要让一个线程在另一个线程修改它时看到一致的值,您可以使用锁定临时保护对象(修改器将等待)或复制对象。 In your example, a copy seems the best option. 在您的示例中,副本似乎是最佳选择。 In python, a slice copy is atomic so does not need any other locking. 在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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.