python - Pyside signals, slots, affinity and object existence -
i have piece of code in custom widget class:
def import_data(self, fname): worker = dataread(fname) readthread = qtcore.qthread(self) worker.movetothread(readthread) readthread.started.connect(worker.read_data) readthread.start()
the 'worker' class looks this:
class dataread(qtcore.qobject): def __init__(self): super(dataread, self).__init__() @qtcore.slot() def read_data(self): print 'hi!'
the code above not work. work if store worker
instance attribute of custom widget class. i.e:
def import_data(self, fname): self.worker = dataread(fname) readthread = qtcore.qthread(self) self.worker.movetothread(readthread) readthread.started.connect(self.worker.read_data) readthread.start()
i can't head round why so?
also, if required, why not required qthread
instance (readthread
) stored attribute?
i've googled , seen lot of talk 'affinity' , 'persistence' nothing explains enough me.
one final question comes mind...if have create worker
instance attribute, not negate movetothread
function call? worker
linked custom widget in main gui thread, when self.worker.read_data
called thread signal, won't executed in main thread?
my mind turning jelly...
the reason need store worker class attribute due persistence of variables have stated. has reference counting. each python object keeps tally of how many references there itself. each new reference make variable, count incremented. every time reference deleted, count decremented. when reference count reaches zero, variable subject garbage collection , freed memory.
your original import_data
function defines worker thread, control returned calling code reference falls out of scope, worker
has reference count reduced zero, , therefore deleted memory. since whole point of threading have have parallel execution, function not wait when call readthread.start()
, continues executing until returns. there no guarantee worker thread finish executing before function returns , reference deleted.
the reason works when make worker
member of class lifetime of reference tied class. reference count not decremented when import_data
returns. worker persist until either containing class deleted, or reference invalidated.
creating worker inside other class no problem movetothread
storing reference thread. not represent thread running.
Comments
Post a Comment