我在这个线程python脚本中使用全局变量是一种很好的做法吗?

时间:2017-02-20 18:17:43

标签: python multithreading global-variables

我正在开发一个使用线程的赋值,我使用全局变量来处理我遇到的问题(比如在线程之间共享变量)。我知道通常不鼓励使用全局变量,所以我想问一下这是否适合使用全局变量。

这是代码。你会发现在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()

2 个答案:

答案 0 :(得分:0)

您已经很好地使用了全局变量。但是,如果将两个全局变量移到函数之外,则代码甚至可以更具可读性。它不会影响它们的范围。你也可以在这里阅读关于全局变量的常见问题,

https://docs.python.org/2/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python

答案 1 :(得分:0)

阿。我看到了问题。 Python不允许在不同的行上进行变量声明和innitialisations。声明并初始化同一行上的所有变量,如下所示,

rand_num = random.randrange(4, 99999)

而不是这样,

global rand_num
    rand_num = random.randrange(4, 99999)

从所有变量中删除global关键字。然后将所有带有global关键字的变量放在所有函数定义之外