CodyKochmann
12/1/2017 - 5:17 PM

nonblocking.py

# by: Cody Kochmann

from multiprocessing import Queue
from functools import wraps

from threading import Thread
try:
    from strict_functions import noglobals, strict_globals
except ImportError:
    exit('failed importing strict_functions\n\nyou can fix this by running:\n    pip install strict_functions')

@strict_globals(
    noglobals=noglobals,
    Queue=Queue,
    Thread=Thread,
    strict_globals=strict_globals,
    wraps=wraps
)
def nonblocking(fn):
    ''' this decorator makes a function nonblocking by putting it behind a queue
        and letting the function run in a seperate thread. Use this for functions
        that you dont care about the output of like logging or things that waste
        a lot of the main threads time like sending data to another server
    '''
    fn_q = Queue()
    @noglobals
    def feeder(fn, q):
        q_g = q.get
        while 1:
            a,k = q_g()
            fn(*a,**k)
    #start_new_thread(feeder, (fn, fn_q))
    Thread(target=feeder, args=(fn, fn_q), daemon=False).start()
    @wraps(fn)
    @strict_globals(fn_q=fn_q)
    def wrapper(*a,**k):
        fn_q.put((a,k))
    return wrapper


@strict_globals(noglobals=noglobals, Queue=Queue, Thread=Thread)
def nonblocking_generator(fn):
    ''' this decorator puts a generator function behind a queue and returns the
        attached queue's get function. this way, you send data to the generator
        like you would any other regular function but underneath the arguments
        are queued and ran by the generator once it can.

        this is useful for times when you have really complex programs and you
        want to split everything off into little async containers.
    '''
    fn_q = Queue()
    gen = fn()
    next(gen) # start the generator
    @noglobals
    def feeder(gen, q):
        g_s = gen.send
        q_g = q.get
        while 1:
            g_s(q_g())
    #start_new_thread(feeder,(gen, fn_q))
    Thread(target=feeder, args=(gen, fn_q), daemon=False).start()
    return fn_q.put

if __name__ == '__main__':
    #=============================================================
    # nonblocking_generator tutorial below
    #=============================================================

    @nonblocking_generator
    @noglobals
    def step2():
        # set up the inner environment here
        print('step2-importing sleep')
        from time import sleep
        # inputs sent to this function are processed in the loop below
        while 1:
            i = yield
            print('step2-recieved', i)
            print('step2-done sleeping for', i)


    @nonblocking_generator
    @strict_globals(step2=step2)
    def step1():
        # set up the inner environment here
        print('step1 importing sleep')
        from time import sleep
        # inputs sent to this function are processed in the loop below
        while 1:
            i = yield
            print('step1 recieved', i)
            print('step1 done sleeping for', i)
            print('step1 sending', i, 'to step2')
            step2(i)

    for i in range(10):
        step1(i)

    print('done sending data to step1')

    #=============================================================
    # nonblocking tutorial below
    #=============================================================

    @nonblocking
    def f2(a):
        print('f2-called with',a)
        print('f2-done sleeping',a)

    @nonblocking
    def f1(a,b):
        print('f1 called with',a,b)
        print('f2 done sleeping',a,b)
        print('f2 sending',a,'to f2')
        f2(a=a)


    for i in range(5):
        f1(a=i,b=i+2)
    print('done sending things to f1')