python_多线程嵌套
Posted hellobigorange
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_多线程嵌套相关的知识,希望对你有一定的参考价值。
"""实现内层线程向列表里追加元素,外层线程调用内层线程,其中外层线程调用1次,内层线程会调用4次(4个内层线程)"""
def inner_thread_function(val):
'''
:param val:
:return: 向内层线程列表中(innerResult:全局变量)添加值
'''
innerResult.append(val)
def inner_thread():
"""内层线程"""
threads = [] # 存放线程
l1=[1,234,4,5]
for val in l1:
# 创建子线程并存放至列表threads
l = threading.Thread(target=inner_thread_function, args=(val,))
threads.append(l)
for t in threads:
# 开启线程
t.start()
for t in threads:
# 主线程等待子线程执行
t.join()
return "innerResult": innerResult
def outer_thread_function(val):
'''
在这里调用内层多线程
:param val:
:return:向外层线程列表(OuterThreadResult:全局变量列表)中调用内层线程,并添加内层线程返回值
'''
data = inner_thread()
OuterThreadResult.append("OuterThreadResult"+str(val): data)
import threading
def out_thread():
'''外层多线程'''
global innerResult
innerResult = []
global OuterThreadResult
OuterThreadResult = []
threads = [] # 存放线程
l2=["1","2","3","4"]
for val in l2:
# 创建子线程并存放至列表threads
l = threading.Thread(target=outer_thread_function, args=(val,))
threads.append(l)
for t in threads:
# 开启线程
t.start()
for t in threads:
# 主线程等待子线程执行
t.join()
return "data": OuterThreadResult
OuterThreadResult = out_thread()
print(OuterThreadResult)
返回值:
‘data’: [‘OuterThreadResult1’: ‘innerResult’: [1, 234, 1, 4, 234, 1, 5, 4, 1, 234, 5, 234, 4, 4, 5, 5], ‘OuterThreadResult2’: ‘innerResult’: [1, 234, 1, 4, 234, 1, 5, 4, 1, 234, 5, 234, 4, 4, 5, 5], ‘OuterThreadResult3’: ‘innerResult’: [1, 234, 1, 4, 234, 1, 5, 4, 1, 234, 5, 234, 4, 4, 5, 5], ‘OuterThreadResult4’: ‘innerResult’: [1, 234, 1, 4, 234, 1, 5, 4, 1, 234, 5, 234, 4, 4, 5, 5]]
以上是关于python_多线程嵌套的主要内容,如果未能解决你的问题,请参考以下文章