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.0123 sec