`

python 线程共享变量

 
阅读更多

#!/usr/bin/env python

"""

多线程中的变量是所有线程中共享的

"""

import threading ,time

 

a = 50

b=50

c=50

d=50

 

 

def printvars():

    print "a =",a

    print "b =",b

    print "c =",c

    print "d =",d

 

def threadcode():

    global a, b, c, d

    a+=50

    b = b+50

    c= 100

    d = "hello"

    print "[childthread] values of variables in child thread:"

    printvars()

 

 

print "[MainThrad] values of variables before child thread:"

printvars()

 

t = threading.Thread(target = threadcode, name = "childthread")

 

t.setDaemon(1)

 

t.start()

 

t.join()

 

print "[MainThrad] values of variables after child thread:"

printvars()

 

输出:

[MainThrad] values of variables before child thread:

a = 50

b = 50

c = 50

d = 50

[childthread] values of variables in child thread:

a = 100

b = 100

c = 100

d = hello

[MainThrad] values of variables after child thread:

a = 100

b = 100

c = 100

d = hello

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics