程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python realizes multi processes, multi threads and multi processes

編輯:Python

One 、 Dependent third-party libraries

        Process library :gevent

         Thread library : threading

        Process library : multiprocessing

Two 、 More cooperation

import gevent,time
def demo1(num):
for i in range(num):
print(' coroutines 1:{:-<30}'.format(111))
# Simulation time operation ,geven Created t After encountering time-consuming operations, the collaboration process will switch to other collaboration processes
gevent.sleep(0.5)
def demo2(num):
for i in range(num):
print(' coroutines 2:{:->30}'.format(222))
gevent.sleep(0.5)
if __name__ == '__main__':
# Create a collaboration object , Internal parameters ( The name of the function pointed to by the coroutine , Parameters to pass )
g1=gevent.spawn(demo1,4)
g2=gevent.spawn(demo2,4)
# Wait for the cooperation process to complete
g1.join()
g2.join()

Print the results :

3、 ... and 、 Multithreading

import threading
from time import sleep
def song(num):
for i in range(num):
print('{:*^30}'.format(' Sing a song '))
sleep(1)
def dance(num):
for i in range(num):
print('{:-^30}'.format(' dance '))
sleep(1)
def main():
# Instantiate two threads , And start the
#target Pointing function ,args Followed by parameters in tuple format , Pass it into the function as an actual parameter
threading.Thread(target=song,args=(5,)).start()
threading.Thread(target=dance,args=(5,)).start()
# Number of printing threads
print(threading.enumerate())
if __name__ =='__main__':
main()

Print the results :

  You can see a main thread and two sub threads

Four 、 Multi process

import multiprocessing,os
from time import sleep
def song(num):
for i in range(num):
print('{:*^30}'.format(' Sing a song '))
# View the status of the process id
print(os.getpid())
sleep(1)
def dance(num):
for i in range(num):
print('{:-^30}'.format(' dance '))
# View the status of the process id
print(os.getpid())
sleep(1)
def main():
# Instantiate two processes , And start the
#target Pointing function ,args Followed by parameters in tuple format , Pass it into the function as an actual parameter
multiprocessing.Process(target=song,args=(5,)).start()
multiprocessing.Process(target=dance, args=(5,)).start()
# View the main process id
print(os.getpid())
if __name__ =='__main__':
main()

Print the results :

You can see a main process number and two sub process numbers


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved