Python教程

python 进程 线程 协程 快速入门

本文主要是介绍python 进程 线程 协程 快速入门,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

进程 multiprocessing

  • Process 类
from multiprocessing import Process

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join() # 让main等待子进程完成
  • Queue(), pool线程池
    队列
from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print(q.get())    # prints "[42, None, 'hello']"
    p.join()

进程池

from multiprocessing import Pool
import time

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(processes=4) as pool:         # start 4 worker processes
        result = pool.apply_async(f, (10,)) # evaluate "f(10)" asynchronously in a single process
        print(result.get(timeout=1))        # prints "100" unless your computer is *very* slow

        print(pool.map(f, range(10)))       # prints "[0, 1, 4,..., 81]"

        it = pool.imap(f, range(10))
        print(next(it))                     # prints "0"
        print(next(it))                     # prints "1"
        print(it.next(timeout=1))           # prints "4" unless your computer is *very* slow

        result = pool.apply_async(time.sleep, (10,))
        print(result.get(timeout=1))        # raises multiprocessing.TimeoutError

线程 threading

  • 创建线程

普通创建

import threading

def run(n):
    print("task", n)

t1 = threading.Thread(target=run, args=("t1",))
t1.start()
t1.join()  # 子线程设置了join方法,主线程就需要等待此子线程

类创建

import threading

class MyThread(threading.Thread):
    def __init__(self, n):
        super(MyThread, self).__init__()  # 重构run函数必须要写
        self.n = n

    def run(self):
        print("task", self.n)

if __name__ == "__main__":
    t1 = MyThread("t1")
    t1.start()
  • setDaemon join
    当设置守护线程时setDaemon(True),意思是子线程是否完整运行对主线程不重要了,主线程结束,子线程也就不执行了。
    当设置子线程阻塞join(timeout)状态时,意思是主线程必须等待子线程,子线程运行时,主线程处于阻塞状态。

协程 asyncio

等待一个协程。以下代码段会在等待 1 秒后打印 "hello",然后 再次 等待 2 秒后打印 "world":

import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

asyncio.create_task() 函数用来并发运行作为 asyncio 任务 的多个协程
修改main函数,执行时间为2秒

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
这篇关于python 进程 线程 协程 快速入门的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!