자바·파이썬·자바스크립트/파이썬 프로그래밍

쓰레딩 예제입니다.

바로이순간 2011. 12. 6. 17:34

from threading import Thread, Lock
from time import sleep
from random import uniform
sum=0
cnt1,cnt2,cnt3=0,0,0
def check(i):
    global sum,cnt1,cnt2,cnt3
    ss=sum
    tt=cnt1+2*cnt2+3*cnt3
    if ss!=tt: print i,tt-ss,  
    else: print '.',
def thread_a():
    global sum,cnt1
    while True:
        sum=sum+1
        cnt1=cnt1+1
        check(1)
        sleep(uniform(0.01,0.5))
def thread_b():
    global sum,cnt2
    while True:
        sum=sum+2
        cnt2=cnt2+1
        check(2)
        sleep(uniform(0.01,0.5))
def thread_c():
    global sum,cnt3
    while True:
        sum=sum+3
        cnt3=cnt3+1
        check(3)
        sleep(uniform(0.01,0.5))
a=Thread(target=thread_a)
b=Thread(target=thread_b)
c=Thread(target=thread_c)
def start_threads():
a.start()
b.start()
c.start()
start_threads()