사용자 도구
관리
로그인
추적:
이 문서는 읽기 전용입니다. 원본을 볼 수는 있지만 바꿀 수는 없습니다. 문제가 있다고 생각하면 관리자에게 문의하세요.
====== 파이썬 쓰레드 문법 ====== 파이썬의 쓰레드와 동기화 객체 문법에 대해 정리한다. ===== 함수 -> 쓰레드 ===== <file python threadEx1.py> # -*- coding: utf-8 -*- import threading, time def testThread(id): for i in range(10): print 'thread(%s) --> %s' % (id, i) time.sleep(0) # context switching testThreads = [] for i in range(3): th = threading.Thread(target=testThread, args=(i,)) th.start() testThreads.append(th) for th in testThreads: th.join() print 'end' </file> ===== 클래스 -> 쓰레드 (상속 이용) ===== <file python threadEx2.py> # -*- coding: utf-8 -*- import threading, time class testThread(threading.Thread): def run(self): for i in range(10): print 'thread(%s) --> %s' % (self.getName(), i) time.sleep(0) # context switching testThreads = [] for i in range(3): th = testThread() th.start() testThreads.append(th) for th in testThreads: th.join() print 'end' </file> ===== Lock ===== <file python threadLockEx.py> # -*- coding: utf-8 -*- import threading, time g_count = 0 class testThread(threading.Thread): def run(self): global g_count for i in range(100): lock.acquire() g_count += 1 lock.release() time.sleep(0) lock = threading.Lock() testThreads = [] for i in range(100): th = testThread() th.start() testThreads.append(th) for th in testThreads: th.join() print g_count </file> ===== Semaphore ===== <file python threadSemEx.py> # -*- coding: utf-8 -*- import threading, time g_count = 0 class testThread(threading.Thread): def run(self): global g_count for i in range(100): sem.acquire() g_count += 1 sem.release() time.sleep(0) sem = threading.Semaphore(3) testThreads = [] for i in range(100): th = testThread() th.start() testThreads.append(th) for th in testThreads: th.join() print g_count </file> ===== Event ===== <file python threadEventEx.py> # -*- coding: utf-8 -*- import threading, time eve = threading.Event() class ready(threading.Thread): def run(self): print 'Ready' eve.set() class waitAndStart(threading.Thread): def run(self): print self.getName(), 'wating...' eve.wait() print self.getName(), 'start' thList = [] for i in range(3): thList.append(waitAndStart()) thList[i].start() ready().start() for th in thList: th.join() print 'exit' </file> ===== 참고 ===== * [[http://blog.naver.com/shw20319?Redirect=Log&logNo=20190208347|[파이썬 기초] 스레드]]
문서 도구
문서 보기
이전 판
역링크
PDF로 내보내기
맨 위로
PDF Export
내용으로 건너뛰기
OBG WiKi
사이트 도구
검색
최근 바뀜
미디어 관리자
사이트맵