U E D R , A S I H C RSS

방울뱀스터디/Thread

Thread 의 정의

쓰레드는 하나의 프로그램(프로세스)안에서 여러가지 일을 동시에 처리해 주는 것을 말합니다.
쉬운 예로 게임을 할때 배경음악이 나오면서도 캐릭터가 움직이고 배경화면 출력됨. 즉 일이 동시에 처리될 때 각각의 일들을 쓰레드라고 합니다.~~!

참고)
프로세스(process) : 쓰레드와 비슷하기는 하지만 좀 더 큰 개념을 말하는데, 서로 다른 프로그램이 동시에 처리될 각각의 프로그램을 가리킴니다..
하나의 프로세스가 여러개의 쓰레드로 이루어 질 수 있는 것입니다.

Thread 모듈

쓰레드를 사용하려면 : 쓰레드로 처리할 부분을 함수로 만들어주고 start_new_thread()로 그 함수로 호출하면 됩니다.

예시1

~cpp 
import thread
i=0
j=0
def f():
    global i
    while 1: i+=1

def g():
    global j
    while 1: j+=1
    
thread.start_new_thread(f,())
thread.start_new_thread(g,())

print 'i=',i
print 'j=',j
print 'i=',i
print 'j=',j

예시2

~cpp 
import thread, time

def counter(id):
    for i in range(5):
        print 'id %s --> %s' % (id, i)
        time.sleep(0.1)

for i in range(5):
    thread.start_new_thread( counter, (i,) )
                        # 5개의 쓰레드를 독립적으로 각각실행

time.sleep(2)           # 잠시대기
print 'Exiting'

변수의 공유

  • 쓰레드의 좋은 점은 전역 변수를 공유할 수 있다는 점이다.
    만약 여러 쓰레드가 한 변수를 동시에 변경하려고 할때 문제가 생길 수 있다.
    값을 갱신하려 하는 중간에 다른 스레드로 교체되면 바르지 못한 정보가 생길경우가 있기 때문이다.

예3

~cpp 
import thread, time
g_count = 0

def counter(id, count):
    global g_count
    for i in range(count):
        print 'id %s -> %s' % (id, i)
        g_count = g_count +1

for i in range(5):
    thread.start_new_thread(counter,(i,5))

time.sleep(3)
print 'Total Counter =', g_count
print 'Exitintg'
(상호배제)
이와 같은 문제점을 해결을 위해서 정보를 갱신하는 동안에는 다른 쓰레드가 그변수에 접근하지 못하도록 하는 것이 필요~!
allow_lock() 함수는 새로운 락 객체를 넘겨준다.(3)
1. thread.acquire() - 락을 얻는다. 일단 하나의 쓰레드가 락을 얻으면 다른 쓰레드는 락을 얻을수 없다.
2. thread.release() - 락을 해제한다. 다른 쓰레드가 이 코드 영역으로 들어갈 수 있는 것을 허락하는 것이다.
3. thread.locked() - 락을 얻었으면 1, 아니면 0을 리턴.

lock = thread.allocate_lock() #여기서 얻은 lock는 모든 쓰레드가 공유해야 한다. (->전역)
# 쓰레드의 코드수행과정
lock.acquire() #락을 얻고 들어간다. 이미 다른 쓰레드가 들어가 있으면 락을 얻을때까지 여기서 자동적을 대기.
g_count = g_count+1 #필요한 코드 수행
lock.release() #락을 해제. 다른 쓰레드가 ㅇ코드영역으로 들어갈 수 있도록 허락한다.

예4

~cpp 
import thread, time
g_count = 0
lock = thread.allocate_lock()
def counter(id, count):
    global g_count
    for i in range(count):
        print 'id %s -> %s' % (id, i)
        lock.acquire()
        g_count = g_count +1
        lock.release()

for i in range(5):
    thread.start_new_thread(counter,(i,5))

time.sleep(3)
print 'Total Counter =', g_count
print 'Exitintg'


~cpp 
from Tkinter import *
import time, thread

def CountTime():
    global i
    i=0
    count=0
    while count<80:
        text.insert(1.0, i)

        text.delete(INSERT)
        #text.update()
        time.sleep(0.1)
        count=count+1


root = Tk()
root.protocol("WM_DELETE_WINDOW", exit)
text=Text(root, height=1)
text.pack()

thread.start_new_thread(CountTime,())

canvas = Canvas(root, width=400, height=300)
canvas.pack()
wall = PhotoImage(file='wall.gif')
canvas.create_image(0, 0, image=wall, anchor=NW)
stop=0

root.mainloop()

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:29:35
Processing time 0.0167 sec