def threadfunc(callback): """this function will call the callback every second""" callback = Async(callback) try: while True: print "!" callback() time.sleep(1) except: print "thread exiting"
import time from Rpyc import SocketConnection, Async c = SocketConnection("localhost") c2 = SocketConnection("localhost") huge_xml = "<blah a='5' b='6'> " * 50000 + " </blah> " * 50000 parseString = Async(c.modules.xml.dom.minidom.parseString) res = parseString(huge_xml) print "while we're waiting for the server to complete, we do other stuff" t = time.time() while not res.is_ready: time.sleep(0.5) # we dont want to use `c`, because it would block us (as the server is blocking) # but `c2` runs on another thread/process, so it wouldn't block print c2.modules.os.getpid() t = time.time() - t print "it took %d seconds" % (t,) print res.result # # note: to improve performance, delete the result when you no longer need it. # this should be done because the server might (as in this case) hold enormous # amounts of memory, which will slow it down # # if you do this: # res = parseString(huge_xml)
# # this demo will show you working with asynch proxies and callback # verison 2.3 removes the AsyncCallback factory, and instead provides a mechanism # where async results can provide a callback. it simplifies the design, so i # went for it. # import time from Rpyc import SocketConnection, Async c1 = SocketConnection("localhost") # f1 is an async proxy to the server's sleep function f1 = Async(c1.modules.time.sleep) # this would block the server for 9 seconds r1 = f1(9) # and this would block it for 11 r2 = f1(11) # of course the client isnt affected (that's the whole point of Async) # but since the same server can't block simultaneously, the second request is # queued. this is a good example of queuing. # now we'll wait for both results to finish. this should print around 20 lines # (more or less, depending on the phase) while not r1.is_ready or not r2.is_ready: print "!" time.sleep(1) print "---"