python - 在 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()
解决方案
请参见下文,例如。我已将变量从 main 传递到并process_function
导入
多处理,os 导入线程process_function
thread_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
推荐阅读
- serialization - Kotlin - 将 JSON 数组序列化为多个类
- c# - 如何获取 ViewResult 的索引?
- swift - 更新 tableview 和 coredata
- reactjs - 如何从对象访问数据并将其放入组件中?
- javascript - 如何访问另一个网页中的一个 php 变量
- php - 使用 GET 参数重写 Wordpress Htaccess URL
- autodesk-forge - 如何从 PHP 下载清单中的项目
- google-cloud-platform - Google Cloud Datastore Emulator - gcloud beta emulators datastore start 无法创建 local_db.bin
- laravel - 如何根据集合形式下拉列表中的选定选项过滤模型集合?
- service-worker - 将服务器转换为 Https 后显示 ServiceWorker 注册失败错误