我正在研究使用线程的任务,并且我使用全局变量来照顾我所遇到的问题(例如在线程之间共享变量)。我知道通常不建议使用全局变量,因此我想询问这是否适当使用全局变量。
这是代码。您会在function1()和function2()中找到全局变量。
from threading import Thread
from time import sleep
import random
import Queue
def getNextPrime(num):
flag = False
while(flag == False):
num = num + 1
flag = True
for i in range(2, num):
if num % i == 0:
flag = False
break
# if we get here num should equal our next prime
return num
def function1(self):
i = 100
global output_buffer
output_buffer = Queue.Queue()
while True:
output_buffer.put("Thread 1: " + str(i))
i -= 1
sleep(1)
def function2(self):
while True:
global rand_num
rand_num = random.randrange(4, 99999)
output_buffer.put("Thread 2: " + str(rand_num))
sleep(1)
def function3(self):
while True:
output_buffer.put("Thread 3: " + str(rand_num / 2.5))
sleep(1)
def function4(self):
prime_num = 1
for i in range(0, 20):
output_buffer.put("Thread 4: " + str(prime_num))
prime_num = getNextPrime(prime_num)
sleep(1)
# if I don't handle output like this I get weird behavior like two threads printing on the same line
def buffer_dump(self):
while True:
while not output_buffer.empty():
print output_buffer.get()
sleep(1)
if __name__ == "__main__":
random.seed()
thread1 = Thread(target=function1, args=(1, ))
thread2 = Thread(target=function2, args=(1, ))
thread3 = Thread(target=function3, args=(1, ))
thread4 = Thread(target=function4, args=(1, ))
output_thread = Thread(target=buffer_dump, args=(1, ))
thread1.start()
output_thread.start()
sleep(2)
thread2.start()
sleep(2)
thread3.start()
sleep(2)
thread4.start()
您很好地使用了全局变量。但是,如果将两个全局变量移到功能之外,则您的代码甚至可以更易读。它不会影响他们的范围。您也可以在此处阅读有关全局变量的常见问题解答,
https://docs.python.org/2/faq/programming.html#what-are-are-the-the-rules-for-local-local-and-global-variables-in-python
ah。我看到了问题。Python不允许在不同行上进行可变声明和iNitialisation。声明并初始化这样的同一行上的所有变量,
rand_num = random.randrange(4, 99999)
不喜欢这样,
global rand_num
rand_num = random.randrange(4, 99999)
从所有变量中删除全局关键字。然后将所有变量放在所有功能定义之外的全局关键字