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

There are several ways to implement Python multithreading

編輯:Python

python There are several ways to implement multithreading , What are they ?

        at present python Provides several multithreading implementations thread,threading,multithreading , among thread The module is low level , and threading The module is right thread Made some packaging , It can be used more conveniently .2.7 Before the release python Thread support Holding is not perfect , Can't use multi-core CPU, however 2.7 Version of python This has been considered for improvement , There is multithreading  modular .threading The module mainly objectifies the operation of some threads , establish Thread Of class.

        Generally speaking , There are two modes of using threads :

        A Create the function to be executed by the thread , Pass this function into Thread In the object , Let it execute ;         B Inherit Thread class , Create a new class, Code to be executed writes run In the function .

The first one is Create a function and pass in Thread In the object

 import threading,time
from time import sleep, ctime
def now() :
return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
print 'start loop', nloop, 'at:', now()
sleep(nsec)
print 'loop', nloop, 'done at:', now()
def main():
print 'starting at:',now()
threadpool=[]
for i in xrange(10):
th = threading.Thread(target= test,args= (i,2))
threadpool.append(th)
for th in threadpool:
th.start()
for th in threadpool :
threading.Thread.join( th )
print 'all Done at:', now()
if __name__ == '__main__':
main() 

The second is to create a new class, Code to be executed writes run In the function .

 import threading ,time
from time import sleep, ctime
def now() :
return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
class myThread (threading.Thread) :
"""docstring for myThread"""
def __init__(self, nloop, nsec) :
super(myThread, self).__init__()
self.nloop = nloop
self.nsec = nsec
def run(self):
print 'start loop', self.nloop, 'at:', ctime()
sleep(self.nsec)
print 'loop', self.nloop, 'done at:', ctime()
def main():
thpool=[]
print 'starting at:',now()
for i in xrange(10):
thpool.append(myThread(i,2))
for th in thpool:
th.start()
for th in thpool:
th.join()
print 'all Done at:', now()
if __name__ == '__main__':
main() 

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