UFO ET IT

파이썬 스레딩.

ufoet 2021. 1. 8. 20:56
반응형

파이썬 스레딩. 스레드를 어떻게 잠그나요?


스레딩 및 동시성의 기본 사항을 이해하려고합니다. 두 개의 스레드가 하나의 공유 리소스에 반복적으로 액세스하려고하는 간단한 경우를 원합니다.

코드:

import threading

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()
count = 0
lock = threading.Lock()

def incre():
    global count 
    lock.acquire()
    try:
        count += 1    
    finally:
        lock.release()

def bye():
    while True:
        incre()

def hello_there():
    while True:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)

    while True:
        print count

if __name__ == '__main__':
    main()

그래서 두 개의 스레드가 있으며 둘 다 카운터를 증가 시키려고합니다. 스레드 'A'가를 호출 incre()하면 lock'A'가 해제 될 때까지 'B'가 액세스하지 못하도록하는 것이 설정 될 것이라고 생각했습니다.

를 실행하면 이것이 사실이 아님을 분명히 알 수 있습니다. 모든 무작위 데이터 경주 증분을 얻습니다.

잠금 개체는 정확히 어떻게 사용됩니까?

편집, 또한 스레드 함수 내부에 잠금을 두려고 시도했지만 여전히 운이 없습니다.


프로세스 속도를 늦추고 조금 더 차단하면 잠금을 사용하는 것처럼 잠금이 거의 작동하고 있음을 알 수 있습니다. 중요한 코드 조각을 자물쇠로 둘러싼 올바른 아이디어를 가지고있었습니다. 다음은 서로가 잠금을 해제하기 위해 기다리는 방법을 보여주기 위해 예제에 대한 작은 조정입니다.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

샘플 출력 :

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

참조 URL : https://stackoverflow.com/questions/10525185/python-threading-how-do-i-lock-a-thread

반응형