[英]Python global variable not updating in threads
I am writing a code to use scale to update a global value VOL. 我正在编写代码以使用scale更新全局值VOL。 The initial value of VOL can be passed to function "check_keys", however, when the scale changes its value, VOL remains unchanged in the thread using function "check_keys".
可以将VOL的初始值传递给函数“ check_keys”,但是,当刻度更改其值时,使用函数“ check_keys”在线程中VOL保持不变。 Where was I doing wrong?
我在哪里做错了?
#!/usr/bin/python
from Xlib.display import Display
from multiprocessing import Process
import threading
import os
import time
import gtk
VOL=1
RUNNING=0
class StatusIcon:
def __init__(self):
global RUNNING
global VOL
self.statusicon = gtk.StatusIcon()
self.statusicon.set_from_stock(gtk.STOCK_HOME)
#self.statusicon.connect("popup-menu", self.right_click_event)
self.win_build()
RUNNING=1
pp = Process(target=self.check_keys)
pp.start()
def quit_program(self, widget):
global RUNNING
RUNNING=0
gtk.main_quit
def scale_moved(self, widget):
global VOL
#print self
#print VOL
VOL = self.scale.get_value()
#print VOL
def check_keys(self):
global VOL
global RUNNING
disp = Display()
hold = 0
samp_inv=0.02
while RUNNING:
print "RUNNING"
print RUNNING
print "VOL"
print VOL
time.sleep(0.2)
def win_build(self):
global VOL
self.window = gtk.Window()
self.window.set_default_size(400, -1)
adjustment = gtk.Adjustment(VOL, 0, 150, 5, 10, 0)
self.scale = gtk.HScale(adjustment)
self.scale.set_digits(0)
self.scale.set_update_policy(gtk.UPDATE_DELAYED)
#VOL=1.
self.visible=1
self.window.connect("destroy", lambda w: w.hide_all())
self.scale.connect("value-changed", self.scale_moved)
self.window.add(self.scale)
self.window.set_title("Typewriter Sound Maker")
self.window.set_position(gtk.WIN_POS_CENTER_ALWAYS)
self.window.show_all()
StatusIcon()
gtk.main()
I think the main problem here is: You are using multiprocessing and not threading. 我认为这里的主要问题是:您正在使用多处理而不是线程。
When you use multiprocessing, python will actually fork a new Process, when that happens it can't access the memory of the other process anymore. 当您使用多重处理时,python实际上会派生一个新的进程,当这种情况发生时,它将无法再访问其他进程的内存。
You have 2 Options here: 您在这里有2个选项:
Select some mechanism to share memory between process, you can find those here: http://docs.python.org/2/library/multiprocessing.html 选择一些在进程之间共享内存的机制,您可以在这里找到: http : //docs.python.org/2/library/multiprocessing.html
or just swap out multiprocessing with threading. 或者只是换掉带有线程的多处理。 http://docs.python.org/2/library/threading.html#module-threading
http://docs.python.org/2/library/threading.html#module-threading
The down side is that it's not really parallel, because Python is doing the context switch, so one part of your app will be blocked. 不利的一面是它不是真正并行的,因为Python正在进行上下文切换,因此您的应用程序的一部分将被阻止。 Anyway, I don't think that concerns you here, because you aren't looking for performance benefits.
无论如何,在这里我不关心您,因为您并不是在寻求性能优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.