比如我们希望对每一个数据记录平方操作的结果:
from threading import Thread
import numpy as np
def calculate_def(value, result_list, i_mark): # 核心计算部分
result_list[i_mark] = value * value
def use_thread(cal_list): # 准备线程的各项操作
_thread_list = [None] * len(cal_list)
_thread_result_list = [None] * len(cal_list)
for _i, cal_value in enumerate(cal_list):
_thread_list[_i] = Thread(target=calculate_def, args=(cal_value, _thread_result_list, _i))
_thread_list[_i].start()
[_sub_thread.join() for _sub_thread in _thread_list]
return _thread_result_list
def main():
# 线程目标,为每一个数据计算平方
cal_list = np.random.randint(1, 10, size=(10))
print(f"原始数据:{cal_list}")
result_list = use_thread(cal_list)
print(f"计算结果:{result_list}")
if __name__ == '__main__':
main()
得到结果:
原始数据:[9 6 5 6 7 8 8 4 3 7]
计算结果:[81, 36, 25, 36, 49, 64, 64, 16, 9, 49]