import threading
def add_numbers(a, b):
"""计算两个数字的和"""
try:
result = a + b
print(f"The sum of {a} and {b} is: {result}")
except Exception as e:
print(f"An error occurred in adding numbers: {e}")
def main():
try:
# 定义任务的参数
num1 = 5
num2 = 10
# 创建线程
thread = threading.Thread(target=add_numbers, args=(num1, num2))
# 启动线程
thread.start()
# 等待线程执行完成
thread.join()
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
线程池:
1、模板
import concurrent.futures
def task_function(arg1, arg2):
"""定义线程要执行的任务函数"""
try:
# 在这里编写任务的具体逻辑
print(f"Task is executing with arguments: {arg1}, {arg2}")
return arg1 + arg2
except Exception as e:
print(f"An error occurred in the task: {e}")
def main():
# 定义任务的参数列表
args_list = [(1, 2), (3, 4), (5, 6)] # 每个元组表示一个任务的参数
try:
# 创建线程池
with concurrent.futures.ThreadPoolExecutor() as executor:
# 提交任务给线程池
futures = []
for args in args_list:
future = executor.submit(task_function, *args)
futures.append(future)
# 获取任务的结果
for future in futures:
try:
result = future.result()
print(f"Task result: {result}")
except Exception as e:
print(f"An error occurred while getting task result: {e}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
这个模板定义了一个 task_function
函数,它接受两个参数并返回它们的和。然后,在 main
函数中,我们定义了一个任务参数列表 args_list
,每个元组表示一个任务的参数。使用 ThreadPoolExecutor
创建了一个线程池,并使用 executor.submit
方法提交任务给线程池。然后,使用 future.result()
方法获取每个任务的结果,并对每个任务的结果进行处理。
2、范例:
import concurrent.futures
def add_numbers(a, b):
"""计算两个数字的和"""
try:
result = a + b
print(f"The sum of {a} and {b} is: {result}")
return result
except Exception as e:
print(f"An error occurred in adding numbers: {e}")
def main():
try:
# 定义任务的参数列表
args_list = [(1, 2), (3, 4), (5, 6)] # 每个元组表示一个任务的参数
# 创建线程池
with concurrent.futures.ThreadPoolExecutor() as executor:
# 提交任务给线程池
futures = [executor.submit(add_numbers, *args) for args in args_list]
# 获取任务的结果
for future in concurrent.futures.as_completed(futures):
try:
result = future.result()
print(f"Task result: {result}")
except Exception as e:
print(f"An error occurred while getting task result: {e}")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
在这个范例中,add_numbers
函数接收两个数字作为参数,并计算它们的和。然后,在 main
函数中,定义了一个任务参数列表 args_list
,每个元组表示一个任务的参数。
使用 ThreadPoolExecutor
创建了一个线程池,并使用 executor.submit
方法提交任务给线程池。然后,使用 concurrent.futures.as_completed
来获取任务的结果,并对每个任务的结果进行处理。