본문 바로가기
프로그램

[파이선] 문제 : 두 조건문 동시 실행 (threading)

by 오디세이99 2022. 11. 27.
728x90
반응형

(문제)

두개의 조건문이 있습니다.
 
if A조건:
   실헹조건: 10분동안 첫번째 A조건문은 정지
if B조건: # A조건문이 10분간 정지해 있어도 B조건문은 작동됨
   실행조건: 10분동안 두번째 B조건문은 정지
 
위와 같이 두개의 조건문중 A나 B가 정지해도 다른 조건문이 실행되는 구조입니다.
10분 뒤에는 다시 A나 B의 조건문이 작동이 되어야 합니다.
 
 
(방법)
import threading
import time
import random

global state

def funcA(low, high):
    global state
    total = 0
    for i in range(low, high):
        total += i
        if i%10000 == 0:
            lock.acquire() # 락을 얻음
            print('[A=',i,'] /total=',total)
            lock.release() # 락을 해제함
            time.sleep(random.randint(1,3))
    print("A Subthread = ", total)


def funcB(low, high):
    global state
    total = 0
    for i in range(low, high):
        total += i
        if i%10000 == 0:
            lock.acquire() # 락을 얻음
            print('[B=',i,'] /total=',total)
            lock.release() # 락을 해제함
            time.sleep(random.randint(1,3))
    print("B Subthread = ", total)

lock = threading.Lock() # 락 객체를 획득함

tA = threading.Thread(target=funcA, args=(1, 100000))
tB = threading.Thread(target=funcB, args=(1, 100000))
tA.start()
tB.start()

print("Main Thread")

728x90
반응형

댓글