2.3경쟁 조건


    멀티스레딩 예제를 하나 더 만들어 보겠습니다.

    코드 10-3 process_thread/multithread_racecondition.py

    import threading
    # 모든 스레드가 공유할 데이터
    g_count = 0          #1
    # 스레드가 실행할 함수
    def thread_main():   #2
        global g_count
        for i in range(100000):
            g_count += 1
    
    threads = [ ]
    
    for i in range(50):  #3
        th = threading.Thread(target = thread_main)
        threads.append(th)
    
    for th in threads:
        th.start()
    
    for th in threads:
        th.join()
    
    print('g_count : {:,}'.format(g_count))  #4
    

    실행결과 1 g_count : 3,339,313


    실행결과 2 g_count : 3,838,022


    실행결과 3 g_count : 3,533,168


    실행결과 4 g_count : 3,725,714

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.