共享variab的Python问题

2024-04-23 18:44:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用来自多个线程和模块的共享队列。我有以下Python代码:

# moda.py

import queue
import modb

q = queue.Queue()

def myPut(x):
    q.put(x)

def main():
    print('moda:', str(id(q)))
    modb.go()
    q.get()


if __name__ == '__main__':
    main()

以及

# modb.py

import moda
import threading


def something():
    print('modb:', str(id(moda.q)))
    moda.myPut('hi')


def go():
    threading.Thread(target = something).start()

something在线程1上被调用,somethingElse在线程2上被调用。在这两个方法中,q的地址是不同的-这就是为什么对get的调用永远不会返回的原因。我怎样才能避免这种情况?是因为循环导入还是因为多线程?你知道吗


Tags: pyimportidgogetqueuemaindef
1条回答
网友
1楼 · 发布于 2024-04-23 18:44:12

The link奥斯汀·菲利普斯在评论中给出了答案:

Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__.

因此,__main__.qmoda.q(导入到modb)是两个不同的对象。你知道吗

使其工作的一种方法是创建这样一个独立的主模块并运行它,而不是moda

# modmain.py

import moda

if __name__ == '__main__':
    moda.main()

但是,您仍然应该考虑将q和其他共享内容放入一个新模块中,然后导入modamodb以避免其他陷阱。你知道吗

相关问题 更多 >