I am writing a code to use scale to update a global value 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". 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.
You have 2 Options here:
Select some mechanism to share memory between process, you can find those here: 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
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. Anyway, I don't think that concerns you here, because you aren't looking for performance benefits.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.