multithreading - Execute Python function in Main thread from call in Dummy thread -


i have python script handles aynchronous callbacks .net remoting. these callbacks execute in dummy (worker) thread. inside callback handler, need call function i've defined in script, need function execute in main thread.

the main thread remote client sends commands server. of these commands result in asynchronous callbacks.

basically, need equivalent of .net's invoke method. possible?

thanks, jim

you want use queue class set queue dummy threads populate functions , main thread consumes.

import queue  #somewhere accessible both: callback_queue = queue.queue()  def from_dummy_thread(func_to_call_from_main_thread):     callback_queue.put(func_to_call_from_main_thread)  def from_main_thread_blocking():     callback = callback_queue.get() #blocks until item available     callback()  def from_main_thread_nonblocking():     while true:         try:             callback = callback_queue.get(false) #doesn't block         except queue.empty: #raised when queue empty             break         callback() 

demo:

import threading import time  def print_num(dummyid, n):     print "from %s: %d" % (dummyid, n) def dummy_run(dummyid):     in xrange(5):         from_dummy_thread(lambda: print_num(dummyid, i))         time.sleep(0.5)  threading.thread(target=dummy_run, args=("a",)).start() threading.thread(target=dummy_run, args=("b",)).start()  while true:     from_main_thread_blocking() 

prints:

from a: 0 b: 0 a: 1 b: 1 b: 2 a: 2 b: 3 a: 3 b: 4 a: 4 

and blocks forever


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -