Python线程、进程、进程池、协程
Python線程,切記Python的GIL特性
import threadingdef func():print(threading.current_thread().getName())passclass MyThread(threading.Thread):def run(self):print(threading.current_thread().getName())def main():print(threading.current_thread().getName())#創建線程thread = threading.Thread(target=func)thread.start()#thread.join()#創建線程t2 = MyThread()t2.start()t2.join()print("programs is finished.")if __name__ == "__main__":main() ?輸出MainThread
Thread-1
Thread-2
programs is finished.
Python進程
輸出?
Main ProcessID:33452
Child ProcessID:616
working...
programs is finished.
Python進程池
輸出
Main ProcessID:27824
Child ProcessID:23104
working...0
Child ProcessID:32968
working...1
Child ProcessID:26228
working...2
Child ProcessID:31036
working...3
Child ProcessID:23104
working...4
Child ProcessID:32968
working...5
Child ProcessID:26228
working...6
Child ProcessID:31036
working...7
Child ProcessID:23104
working...8
Child ProcessID:32968
working...9
programs is finished.
Python協程一
Python協程二
import asyncioasync def hello():print("hello the world")r = await asyncio.sleep(1)print("hello again")def main():loop = asyncio.get_event_loop()"""tasks = [asyncio.ensure_future(hello()),]loop.run_until_complete(asyncio.wait(tasks))"""print("begin")loop.run_until_complete(hello())print("end")loop.close()print("program is finished.")if __name__ == "__main__":main()
輸出
begin
hello the world
hello again
end
program is finished.
總結
以上是生活随笔為你收集整理的Python线程、进程、进程池、协程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scala的传值参数和传名参数
- 下一篇: systemd教程推荐