>  기사  >  백엔드 개발  >  Python에서 멀티스레딩을 구현하는 방법

Python에서 멀티스레딩을 구현하는 방법

高洛峰
高洛峰원래의
2017-03-02 16:13:221397검색

현재 Python은 스레드, 스레딩, 멀티스레딩 등 여러 가지 멀티스레딩 구현 방법을 제공합니다. 스레드 모듈은 상대적으로 낮은 수준이며 스레드 모듈은 스레드를 래핑하여 더 편리하게 사용할 수 있습니다.

2.7 버전 이전에는 Python의 스레드 지원이 충분하지 않아 멀티 코어 CPU를 활용할 수 없었습니다. 그러나 Python 2.7 버전에서는 이를 개선하는 것을 고려하여 멀티스레딩 모듈이 등장했습니다. 스레딩 모듈은 주로 일부 스레드 작업을 객체화하고 Thread 클래스를 생성합니다. 일반적으로 스레드를 사용하는 데는 두 가지 모드가 있습니다.

A는 스레드에 의해 실행될 함수를 생성하고 이 함수를 Thread 개체에 전달한 다음 실행되도록 합니다.
B 상속 스레드 클래스, 새 클래스를 만들고 실행할 코드를 실행 함수에 작성합니다.

이 글에서는 두 가지 구현 방법을 소개합니다.
첫 번째 방법은 함수를 생성하여 Thread 객체
t.py 스크립트 콘텐츠

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()

thclass.py 스크립트 내용:

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()

위 내용이 전체 내용인가요? 이 글이 여러분에게 도움이 되기를 바랍니다. Python 프로그래밍을 배우는 데 도움이 될 것입니다.

파이썬의 멀티스레딩 구현 방법과 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!



성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.