Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

multithreading - Change global variable in Python in another thread

I want change global variable in module1.py by module2.py.

module1.py

#!/usr/bin/env python
import threading
import module2  as module22
import time

values=True

def main():
 print "m"


def thread():
 while(values):
  print "moduel1"
  time.sleep(0.50)
 print "END PROGRAM"

def change():
 print "change"
 values=False

if __name__ == "__main__":

 t2=threading.Thread(target=module22.main())
 t1=threading.Thread(target=thread())



 t1.start()
 t2.start()


 t1.join()
 t2.join()

module2.py

#!/usr/bin/env python
import module1 as module11


def main():
 print "module2"

 module11.change()


if __name__ == "__main__":
  main()

When I run sudo python module1.py:

Result is here

module2
change
moduel1
moduel1..

I want get result

 module2
 change
 END PROGRAM
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to declare values as global, if you dont do this, the variable is handled as new local variable.

def change():
  global values
  print "change"
  values=False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...