翼度科技»论坛 编程开发 python 查看内容

Python技巧之四种多线程应用分享

4

主题

4

帖子

12

积分

新手上路

Rank: 1

积分
12
在Python中,多线程是实现并发的一种方式。多线程可以让程序在同一时间内进行多个任务,从而提高程序的效率和执行速度。
本文将介绍Python中多线程的所有方式,包括使用threading模块、使用concurrent.futures模块、使用multiprocessing模块以及使用asyncio模块。

1.使用threading模块

Python中的threading模块提供了多线程编程的基本支持。使用该模块可以创建和管理线程,从而实现并发执行。下面是使用threading模块实现多线程的示例代码:
  1. import threading
  2. def worker():
  3.     print('Worker thread started')
  4.     # do some work here
  5.     print('Worker thread finished')
  6. if __name__ == '__main__':
  7.     print('Main thread started')
  8.     # create a new thread
  9.     t = threading.Thread(target=worker)
  10.     # start the new thread
  11.     t.start()
  12.     print('Main thread finished')
复制代码
在上面的代码中,我们首先定义了一个worker函数,该函数会在一个新的线程中执行。
然后,在主线程中创建了一个新的线程t,并将worker函数作为该线程的目标。
最后,通过调用start方法来启动新线程。运行上面的代码,输出结果如下:
  1. Main thread startedWorker thread startedMain thread finishedWorker thread finished
复制代码
从上面的输出结果可以看出,程序先执行了主线程中的代码,然后创建了一个新的线程,并在新线程中执行worker函数。
主线程和新线程是并行执行的,因此程序的执行速度得到了提高。

2.使用concurrent.futures模块

concurrent.futures模块是Python 3中的新模块,它提供了线程池和进程池的实现。使用该模块可以更方便地实现并行执行。
下面是使用concurrent.futures模块实现多线程的示例代码:
  1. import concurrent.futures
  2. def worker():
  3.     print('Worker thread started')
  4.     # do some work here
  5.     print('Worker thread finished')
  6. if __name__ == '__main__':
  7.     print('Main thread started')
  8.     # create a thread pool
  9.     with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
  10.         # submit worker function to the pool
  11.         future = executor.submit(worker)
  12.         print('Main thread finished')
复制代码
在上面的代码中,我们首先定义了一个worker函数,该函数会在一个新的线程中执行。
然后,在主线程中创建了一个线程池executor,并设置最大线程数为2。接着,通过调用submit方法将worker函数提交给线程池。
最后,我们输出了一条信息,表示主线程已经执行完毕。运行上面的代码,输出结果如下:
  1. Main thread startedMain thread finishedWorker thread startedWorker thread finished
复制代码
从上面的输出结果可以看出,程序先执行了主线程中的代码,然后通过线程池执行了worker函数。线程池会自动管理线程的创建和销毁,从而使程序更加高效。

3.使用multiprocessing模块

Python中的multiprocessing模块提供了多进程编程的支持。使用该模块可以在不同的进程中执行任务,从而实现并发执行。
下面是使用multiprocessing模块实现多线程的示例代码:
  1. import multiprocessing
  2. def worker():
  3.     print('Worker process started')
  4.     # do some work here
  5.     print('Worker process finished')
  6. if __name__ == '__main__':
  7.     print('Main process started')
  8.     # create a new process
  9.     p = multiprocessing.Process(target=worker)
  10.     # start the new process
  11.     p.start()
  12.     print('Main process finished')
复制代码
在上面的代码中,我们首先定义了一个worker函数,该函数会在一个新的进程中执行。然后,在主进程中创建了一个新的进程p,并将worker函数作为该进程的目标。
最后,通过调用start方法来启动新进程。运行上面的代码,输出结果如下:
  1. Main process startedMain process finishedWorker process startedWorker process finished
复制代码
从上面的输出结果可以看出,程序先执行了主进程中的代码,然后创建了一个新的进程,并在新进程中执行worker函数。
主进程和新进程是并行执行的,因此程序的执行速度得到了提高。

4.使用asyncio模块

Python中的asyncio模块提供了异步编程的支持。使用该模块可以实现协程,从而在单线程中实现并发执行。
下面是使用asyncio模块实现多线程的示例代码:
  1. import asyncio
  2. async def worker():
  3.     print('Worker task started')
  4.     # do some work here
  5.     print('Worker task finished')
  6. if __name__ == '__main__':
  7.     print('Main task started')
  8.     # create a new event loop
  9.     loop = asyncio.get_event_loop()
  10.     # run the worker coroutine
  11.     loop.run_until_complete(worker())
  12.     # close the event loop
  13.     loop.close()
  14.     print('Main task finished')
复制代码
在上面的代码中,我们首先定义了一个异步函数worker,该函数会在一个协程中执行。
然后,在主任务中创建了一个新的事件循环loop,并通过调用run_until_complete方法来运行worker协程。
最后,我们关闭了事件循环。运行上面的代码,输出结果如下:
  1. Main task startedWorker task startedWorker task finishedMain task finished
复制代码
从上面的输出结果可以看出,程序先执行了主任务中的代码,然后通过事件循环执行了worker协程。
协程是在单线程中执行的,因此程序的执行速度得到了提高。
5.总结
本文介绍了Python中多线程的所有方式,包括使用threading模块、使用concurrent.futures模块、使用multiprocessing模块以及使用asyncio模块。
不同的方式适用于不同的场景,可以根据需要选择最合适的方式。
多线程编程可以提高程序的效率和执行速度,但需要注意线程安全和锁的使用。
到此这篇关于Python技巧之四种多线程应用分享的文章就介绍到这了,更多相关Python多线程内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

来源:https://www.jb51.net/article/283783.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具