[[TableOfContents]] = 참고 사이트 = * [http://linuxgazette.net/107/pai.html] = 기본 = * 아래는 간단하게 쓰레드 하나를 생성하는 예제 {{{~cpp import time import thread def myfunction(string,sleeptime,*args): while 1: print string time.sleep(sleeptime) #sleep for a specified amount of time. if __name__=="__main__": thread.start_new_thread(myfunction,("Thread No:1",2)) while 1:pass }}} == Lock == * lock이 왜 필요하나? -> 하나의 공용 자원을 여러 스레드가 동시에 사용하면 문제가 생길수 있다. 그래서 공용자원을 사용할때는 락을 걸고 사용하고 사용하고 나서는 락을 푼다. * 문제 상황 예 : count 변수를 각 쓰레드들이 1식 증가를 시키는데 한 스레드가 증가 시키는 동안 다른 스레드도 동시에 증가 시키다 보면 원래 2 증가 해야하는데 1증가 하는 수가 생긴다.. {{{~cpp import time import thread def myfunction(string,sleeptime,lock,*args): while 1: #entering critical section lock.acquire() print string," Now Sleeping after Lock acquired for ",sleeptime time.sleep(sleeptime) print string," Now releasing lock and then sleeping again" lock.release() #exiting critical section time.sleep(sleeptime) # why? if __name__=="__main__": lock=thread.allocate_lock() thread.start_new_thread(myfunction,("Thread No:1",2,lock)) thread.start_new_thread(myfunction,("Thread No:2",2,lock)) while 1:pass }}} * 위 소스에서 why 부분,, 왜 sleep을 넣었을까?(만약 저것을 빼면 한쓰레드가 자원을 독점하게 된다) -> Python 은 threadsafe 하지 않다. Python에서는 자바처럼 스레드가 문법의 중요한 위치를 차지하고 있지 않다. 그것보다 이식 가능성을 더 중요하게 생각한다. * 모든 built-in 함수가 다른 쓰레드가 실행할수 있도록 I/O에 대한 block waiting 을 하는 것은 아니다.(time.sleep(), file.read(), select.select()) 은 예상대로 작동한다) * lock 상태에 있는 acquire() 함수에 대하여 interrupt 하는것은 가능하지 않다. (키보드 인터럽트도 lock을 얻고 나서야 일어난다.) * 그래서 아래와 같은 소스는 starvation을 일으킨다. {{{~cpp hile 1: lock.acquire() ..... #some operation ..... lock.release() }}} ---- [Python]