Python Other
Other
多线程
Python多线程是一种并发编程的技术,在同一时间内执行多个线程,从而提高程序的效率和响应速度。在Python中,可以使用
threading模块来创建和管理线程。
-
下面是一个简单的例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import threading def print_numbers(): for i in range(1, 11): print(i) def print_letters(): for i in range(ord('a'), ord('k')): print(chr(i)) t1 = threading.Thread(target=print_numbers) t2 = threading.Thread(target=print_letters) t1.start() t2.start() t1.join() t2.join()
-
该程序创建了两个线程
t1和t2,分别执行print_numbers函数和print_letters函数。通过调用start()方法启动线程,join()方法等待线程结束。在上述例子中,t1和t2会同时执行,因此输出结果可能是交替出现的数字和字母。 -
需要注意的是,在多线程编程中,由于多个线程共享相同的资源(如全局变量或文件),因此可能会出现竞争条件和死锁等问题。因此,在编写多线程程序时,需要特别小心,确保线程安全。
-
另外,Python还提供了
multiprocessing模块,可以将任务分配给多个进程并行处理,更适合CPU密集型任务。与多线程不同,每个进程拥有独立的内存空间,不会共享资源。
协程
Python 协程是一种轻量级的并发编程方式,可以通过使用
async和await关键字来实现。协程是可以暂停和恢复执行的函数,可以让我们更方便地进行异步编程。
-
下面是一个简单的 Python 协程示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import asyncio async def foo(): print('Start foo') await asyncio.sleep(1) print('Finish foo') async def bar(): print('Start bar') await asyncio.sleep(2) print('Finish bar') async def main(): # 并发执行 foo 和 bar 协程 tasks = [asyncio.create_task(foo()), asyncio.create_task(bar())] await asyncio.gather(*tasks) if __name__ == '__main__': asyncio.run(main())
-
这个示例定义了三个协程函数
foo、bar和main,其中foo和bar分别打印一些信息并等待一段时间,main函数则同时调用foo和bar协程,并使用asyncio.gather()方法并发运行这两个协程。最终输出结果为:1 2 3 4
Start foo Start bar Finish foo Finish bar
这说明在 3 秒钟内,同时执行了
foo和bar协程,并且在各自的等待时间结束后,按顺序输出了相应的结果。
This post is licensed under
CC BY 4.0
by the author.