Skip to content

Instantly share code, notes, and snippets.

@shoveller
Last active August 29, 2015 14:02
Show Gist options
  • Save shoveller/b74f087d5cdc1af3f501 to your computer and use it in GitHub Desktop.
Save shoveller/b74f087d5cdc1af3f501 to your computer and use it in GitHub Desktop.
Thread in python 2.7. 파이썬2.7에서 쓰레드 구현하기
# -*- coding: UTF-8 -*-
__author__ = 'cinos81'
import threading
import time
#함수를 쓰레드로 만들 때의 공유자원을 가정한 변수
globalResource = 0
#함수형 쓰레드. 사실 그 어떤 함수가 오더라도 관계가 없음.
#단 이 함수에서만 사용하는 상태변수를 격납하기 어렵다는 단점이 있다.
def clock_usingGlobalVariable(interval):
#함수에서는 지역변수가 기본이라 global키워드를 사용해서 global변수를 사용한다고 명시적으로 지정해 줄 필요가 있음.
global globalResource
while True:
globalResource += 1
print 'this is {0}'.format(globalResource)
time.sleep(interval)
#클래스형 쓰레드. 잘 알려진 방법으로 만들 수 있다는 것이 장점.
class Clock(threading.Thread):
def __init__(self, interval):
super(Clock, self).__init__()
self.resource = 0
self.interval = interval
#run 프로토콜을 구현하는 것만으로 ok
def run(self):
while True:
self.resource += 1
print 'this is {0}'.format(self.resource)
time.sleep(self.interval)
if __name__ == '__main__':
# 파이썬에서 쓰레드 생성시 함수형으로 구현할 수도 있고
# thread = threading.Thread(target=clock_usingGlobalVariable, args=(1,))
# 객체형으로 구현도 가능
# 객체 스타일로 구현하면 관련된 변수를 격납할 수 있다는 장점이 있다.
thread = Clock(1)
thread.demon = True
thread.start()
@shoveller
Copy link
Author

함수형으로 쓰레드를 구현한 예제들이 많지만, 클래스를 정식으로 지원하는 언어에서 굳이 함수형으로 개발하는 것도 고집인것 같다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment