2012. 8. 9. 01:30

thread를 이용할 경우 혹은 간혹 전역변수가 필요할 때가 있다.

python은 일반적으로 모든 변수들을 지역변수로 사용한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/python
 
import sys
import threading
 
global_value = 0
local_value = 0
 
def function(number, local_value) :
    global global_value
 
    global_value += 10
    local_value += 10
 
    sys.stdout.write("[Thread #%d] global_value: %d\n"
            % (number, global_value))
    sys.stdout.write("[Thread #%d] local_value: %d\n"
            % (number, local_value))
 
def main(thread_count) :
    threads = []
    for i in range(thread_count) :
        print "Create Thread #%d" % i
        threads.append(threading.Thread(target=function,
            args=(i,local_value)))
 
    for i in range(thread_count) :
        print "Start Thread #%d" % i
        threads[i].start()
 
    for i in range(thread_count) :
        threads[i].join()
        print "End Thread #%d" % i
 
if __name__ == "__main__" :
    main(5)
전역변수와 지역변수를 사용한 예제다.
사용하려는 곳에서 global을 이용하여 해당 변수가 전역변수라는 것을 알린다.

10번째 줄을 주석처리해보면 할당되지 않은 영역을 참조했다는 에러 메시지를 확인할 수 있다.

Posted by k1rha