Python의 다중 프로세스 및 다중 스레드 예제 (2) 프로그래밍 방법

零下一度
풀어 주다: 2017-06-01 10:01:10
원래의
1674명이 탐색했습니다.

 이전 장에서는 Python 다중 프로세스 프로그래밍의 몇 가지 기본 방법을 배웠습니다. 즉, 크로스 플랫폼 다중 프로세스 모듈 다중 처리에서 제공하는 프로세스, 풀, 큐, 잠금, 파이프 및 기타 클래스를 사용하여 하위 프로세스 생성을 구현하고 프로세스 풀(일괄적으로 하위 프로세스 생성)을 처리하고 최대 하위 프로세스 수를 관리합니다. 및 프로세스 간 통신. 이 장에서는 Python의 다중 스레드 프로그래밍 방법에 대해 배웁니다.

1. 스레딩

스레드는 운영 체제에서 작업을 수행하는 가장 작은 단위입니다. 스레딩 모듈은 Python 표준 라이브러리에 제공되어 다중 스레드 프로그래밍을 매우 편리하게 지원합니다.

다음은 스레딩을 사용하여 멀티스레딩을 구현하는 코드입니다.

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7  8 import threading, time 9 10 def test(index):11     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))12     print 'thread %s starts.' % threading.current_thread().name13     print 'the index is %d' % index14     time.sleep(3)15     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))16     print 'thread %s ends.' % threading.current_thread().name17 18 if name == "main":19     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))20     print 'thread %s starts.' % threading.current_thread().name21     #创建线程22     my_thread = threading.Thread(target = test, args=(1,) , name= 'zni_feng_thread')23     #等待2s24     time.sleep(2)25     #启动线程26     my_thread.start()27     #等待线程结束28     my_thread.join()29     print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))30     print 'thread %s ends.' % threading.current_thread().name
로그인 후 복사

출력 결과는 다음과 같습니다.

2017-01-12 22:06:32
thread MainThread starts.
2017-01-12 22:06:34
thread zni_feng_thread starts.
the index is 1
2017-01-12 22:06:37
thread zni_feng_thread ends.
2017-01-12 22:06:37
thread MainThread ends.
[Finished in 5.1s]
로그인 후 복사

그 중 스레딩 모듈의 current_thread()함수는 현재 스레드의 인스턴스를 반환합니다.

2. 잠금

멀티 프로세스와 멀티 스레드의 가장 큰 차이점은 멀티 프로세스에서는 동일한 변수가 각 프로세스에 복사본을 가지며 서로 영향을 미치지 않는다는 것입니다. 멀티스레딩에서는 모든 변수가 모든 스레드에서 공유되므로 모든 공유 변수는 모든 스레드에서 수정할 수 있습니다. 따라서 스레드 간에 데이터를 공유할 때 가장 큰 위험은 여러 스레드가 동시에 변수를 변경한다는 것입니다. 이 문제를 해결하기 위해 스레딩 모듈의 Lock 클래스를 사용하여 공유 변수를 잠글 수 있습니다.

먼저 여러 스레드를 사용하여 잠금 없이 동일한 공유 변수를 작성하는 예를 살펴보겠습니다.

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7 import threading 8  9 class Account:10     def init(self):11         self.balance = 012 13     def add(self):14         for i in range(0,100000):15             self.balance += 116 17     def delete(self):18         for i in range(0,100000):19             self.balance -=1 
20 21 if name == "main":22     account  = Account()23     #创建线程24     thread_add = threading.Thread(target=account.add, name= 'Add')25     thread_delete = threading.Thread(target=account.delete, name= 'Delete')26 27     #启动线程28     thread_add.start()29     thread_delete.start()30     31     #等待线程结束32     thread_add.join()33     thread_delete.join()34 35     print 'The final balance is: ' + str(account.balance)
로그인 후 복사

실행 결과는 다음과 같습니다.

The final balance is: -51713
[Finished in 0.1s]
로그인 후 복사

실행될 때마다 최종 결과가 달라지는 것을 확인할 수 있으며, 0이 아닙니다. 이는 서로 다른 스레드가 동일한 변수를 동시에 수정하면 충돌이 발생하고 일부 중간 변수가 순서대로 사용되지 않기 때문입니다.

이제 Lock을 사용하여 프로그램을 잠급니다.

 1 #!/usr/bin/python 2 # -*- coding: utf-8 -* 3 author = 'zni.feng' 4 import  sys 5 reload (sys) 6 sys.setdefaultencoding('utf-8') 7 import threading 8  9 class Account:10     def init(self):11         self.balance = 012 13     def add(self, lock):14         #获得锁15         lock.acquire()16         for i in range(0,100000):17             self.balance += 118         #释放锁19         lock.release()20 21     def delete(self, lock):22         #获得锁23         lock.acquire()24         for i in range(0,100000):25             self.balance -=1 
26         #释放锁27         lock.release()28 29 30 if name == "main":31     account  = Account()32     lock = threading.Lock()33     #创建线程34     thread_add = threading.Thread(target=account.add, args=(lock, ), name= 'Add')35     thread_delete = threading.Thread(target=account.delete, args=(lock, ), name= 'Delete')36 37     #启动线程38     thread_add.start()39     thread_delete.start()40     41     #等待线程结束42     thread_add.join()43     thread_delete.join()44 45     print 'The final balance is: ' + str(account.balance)
로그인 후 복사

실행 횟수에 관계없이 잔액 결과는 0입니다. 각 잔액 계산 결과를 인쇄해 보면 한 스레드가 실행을 시작할 때 다른 스레드는 이전 스레드가 실행을 완료할 때까지(정확히 말하면 lock.release() 실행이 완료될 때까지) 시작하기 전에 대기한다는 사실도 알 수 있습니다. . 구현하다.

The final balance is: 0
[Finished in 0.1s]
로그인 후 복사

【관련 권장 사항】

1. Python의 다중 프로세스 및 다중 스레딩 예제(1)

2. Python에서 다중 스레딩 대신 다중 프로세스를 사용하는 것이 좋습니다? 멀티 프로세스 사용을 권장하는 이유 공유

3. Python에서는 멀티 프로세스가 더 빠른가요, 아니면 멀티 스레드가 더 빠른가요?

4. Python 프로세스, 스레드 및 코루틴에 대한 자세한 소개

5. Python 동시 프로그래밍 스레드 풀/프로세스 풀

위 내용은 Python의 다중 프로세스 및 다중 스레드 예제 (2) 프로그래밍 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!