Python线程、进程、进程池、协程

来源:互联网 发布:算法导论和数据结构 编辑:程序博客网 时间:2024/05/16 01:59

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进程

import multiprocessingimport osdef worker():    print( "Child ProcessID:" + str(os.getpid()) )    print("working...")def main():    print( "Main ProcessID:" + str(os.getpid()) )    #创建进程    p = multiprocessing.Process(target=worker)    p.start();    p.join();    print("programs is finished.")if __name__ == "__main__":    main()
 
输出 

Main ProcessID:33452
Child ProcessID:616
working...
programs is finished.


Python进程池

import multiprocessingfrom multiprocessing import Poolimport osimport timedef worker(i):    print( "Child ProcessID:" + str(os.getpid()) )    print("working..." + str(i))    time.sleep(1)def callback(arg):    print(arg)def main():    print( "Main ProcessID:" + str(os.getpid()) )    pool = Pool(4)    #创建进程    for i in range(10):        pool.apply(func=worker, args=(i,))        #pool.apply(func=worker, args=(i,), callback=callback)    print("programs is finished.")if __name__ == "__main__":    main()

输出

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协程一

import asyncio@asyncio.coroutinedef hello():    print("hello the world")    r = yield from 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()

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.


0 0
原创粉丝点击