我正在编写一个代码来使用scale来更新全局值VOL。 VOL的初始值可以传递给函数“check_keys”,但是,当比例改变其值时,VOL在线程中使用函数“check_keys”保持不变。我哪里做错了?
#!/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()
答案 0 :(得分:4)
我认为这里的主要问题是:您正在使用多处理而不是线程。
当你使用多处理时,python实际上会派生一个新的进程,当它发生时,它就不能再访问另一个进程的内存了。
这里有2个选项:
选择一种在流程之间共享内存的机制,您可以在此处找到:http://docs.python.org/2/library/multiprocessing.html
或者只是用线程换出多处理。 http://docs.python.org/2/library/threading.html#module-threading
缺点是它并不是真正的并行,因为Python正在进行上下文切换,因此应用程序的某个部分将被阻止。无论如何,我认为这不关心你,因为你不是在寻找性能优势。