首页 > 解决方案 > 在 Python 中的进程产生的线程之间共享一个变量

问题描述

我想与从程序主程序产生的进程的主线程和从同一进程产生的线程共享一个变量。

我要共享的变量不是数组或 int 之类的简单对象。对于我的情况,这是一个套接字 zmq.socket 对象,但它可以是任何 python 对象。这个共享变量应该只能在生成的进程中访问,因此声明为全局变量是不可接受的。

提前致谢。

def process_function():
    
    
    # print init
    pid = os.getpid()
    print("PROCESS STARTS", pid)

    var = #this want to use in thread
    # create a thread
    thread = threading.Thread(target=thread_function)
    thread.start()
    ... # stuff
    thread.join()
def thread_function():

    # print start prompt
    print("THREAD STARTS")
    
    #do stuff with var
# 在主
如果 __name__ == '__main__':
        p = multiprocessing.Process(target=process_function, args=())
        p.start()
        #做东西
        p.join()

编辑 1

我发现了一种使用全局关键字的方法。

def process_function():
    global var # this is new
    #this var is only global within process, if you create
    #many processes each will have its own var

    # print init
    pid = os.getpid()
    print("PROCESS STARTS", pid)

    var = #this want to use in thread
    # create a thread
    thread = threading.Thread(target=thread_function)
    thread.start()
    ... # stuff
    thread.join()
def thread_function():
    global var #this is new as well
    # print start prompt
    print("THREAD STARTS")
    
    #do stuff with var
# 在主
如果 __name__ == '__main__':
        p = multiprocessing.Process(target=process_function, args=())
        p.start()
        #做东西
        p.join()

标签: pythonpython-multiprocessingpython-multithreading

解决方案


请参见下文,例如。我已将变量从 main 传递到并process_function导入 多处理,os 导入线程process_functionthread_function

def process_function(input):
    print('2. inside process_function')
    print(input)
    pid = os.getpid()
    print("PROCESS STARTS", pid)
    var =  'variable from process func to thread'
    # create a thread
    thread = threading.Thread(target=thread_function, args=(var,))
    thread.start()
    thread.join()


def thread_function(msg):
    print('3. inside thread_function')
    # print start prompt
    print("THREAD STARTS")
    print(msg)

    # do stuff with var


# In main
if __name__ == '__main__':
    print('1. inside main')
    inputs = 'varaible from main'
    p = multiprocessing.Process(target=process_function, args=(inputs,))
    p.start()
    # do stuff
    p.join()

输出:

1. inside main
2. inside process_function
varaible from main
PROCESS STARTS 19372
3. inside thread_function
THREAD STARTS
variable from process func to thread

推荐阅读