示例程序

比如我们希望对每一个数据记录平方操作的结果:

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]
Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐