# the function that will extract shared global variables def extract(globals_dict: Dict[str, Any]) -> Dict[str, Any]: return {'a': globals_dict['a']} # extract a # the function that will merge shared global variables def merge(old_globals: Dict[str, Any], new_globals: Dict[str, Any]) -> None: old_globals.update(new_globals) # simply overwrite the old globals # 'a' before update print("global 'a' was", a) print() # spawn a snakefish thread and join it t = snakefish.Thread(f, extract, merge) print("thread alive?", t.is_alive()) t.start() print("thread alive?", t.is_alive()) t.join() print("thread alive?", t.is_alive()) print() # check exit status and get the return value assert (t.get_exit_status() == 0) print("thread exit status:", t.get_exit_status()) print("result of f():", t.get_result()) print("global 'a' is", a) # 'a' after update # release resources t.dispose()
# blocking receive print("thread #3: receiving an object...") received2 = channel.receive_pyobj(True) print("thread #3: timestamps are %s and %s" % (received1[0], received2[0])) if received1[0] <= received2[0]: print("thread #3: %s occurred before %s" % (received1[1], received2[1])) else: print("thread #3: %s occurred before %s" % (received2[1], received1[1])) # spawn 3 snakefish threads t1 = snakefish.Thread(f1) t2 = snakefish.Thread(f2) t3 = snakefish.Thread(f3) t1.start() t2.start() t3.start() # join the threads and check exit status t1.join() assert (t1.get_exit_status() == 0) print("thread #1 exit status:", t1.get_exit_status()) print("result of f1():", t1.get_result()) t2.join() assert (t2.get_exit_status() == 0)
import time from typing import * # use type hints to make signatures clear import snakefish # the function that will be executed on a snakefish thread def f() -> List[int]: print("f() will sleep for 500 ms") time.sleep(0.5) return [i for i in range(200)] # return a large list # spawn a snakefish thread t = snakefish.Thread(f) t.start() # try to join the thread and time it start = time.time() while True: if t.try_join(): print("try_join() successful") break else: print("try_join() unsuccessful, sleep for 100ms") time.sleep(0.1) print("try_join() took %s sec" % (time.time() - start)) # check exit status and get the return value assert (t.get_exit_status() == 0) print("thread exit status:", t.get_exit_status())