如何在python中跨线程共享全局变量?

use*_*094 9 python multithreading

我想结束使用全局变量在单独的线程中运行的循环.但是这段代码似乎没有停止循环中的线程.我希望该程序不再打印'.' 2秒后,它仍然无限期地运行.

我在这里做了一些根本错误的事吗?

import time
import threading
run = True

def foo():
    while run:
        print '.',

t1 = threading.Thread(target=foo)
t1.run()
time.sleep(2)
run = False
print 'run=False'
while True:
    pass
Run Code Online (Sandbox Code Playgroud)

Boa*_*niv 5

  1. 您正在foo()通过调用在主线程上执行t1.run().你应该打个电话t1.start().

  2. 你有两个定义foo()- 无所谓,但不应该存在.

  3. 你没有sleep()在线程循环内部(在foo()中).这非常糟糕,因为它占用了处理器.你应该至少把time.sleep(0)(释放时间片给其他线程),如果不让它再睡一会儿.

这是一个有效的例子:

import time
import threading
run = True

def foo():
    while run:
        print '.',
        time.sleep(0)

t1 = threading.Thread(target=foo)
t1.start()
time.sleep(2)
run = False
print 'run=False'
while True:
    pass
Run Code Online (Sandbox Code Playgroud)