Package: pythreadworker
A threading library written in python. Help you build threaded app.This module was originally included inComicCrawler.FeaturesPause, resume, stop, and restart a thread.Support child threads.Easily run asynchronous task across multiple threads.Communicate between threads with events.Use channel to broadcast events.Installpip install pythreadworkerUsage exampleBasic operations and event:#! python3# Always use worker.sleep. pyWorker would process event queue during# waiting.fromworkerimportcreate_worker,listen,sleep@create_workerdefincreaser():count=1@listen("SET_VALUE")def_(event):nonlocalcount# you don't need a lock to manipulate `count`count=event.datawhileTrue:print(count)# because the listener and the while loop are in the same threadcount+=1sleep(1)whileTrue:command=input("input command: ")ifcommand=="start":increaser.start()elifcommand=="stop":increaser.stop()elifcommand=="pause":increaser.pause()elifcommand=="resume":increaser.resume()elifcommand.startswith("set"):increaser.fire("SET_VALUE",int(command[4:]))elifcommand=="exit":increaser.stop()breakAsync task:#! python3fromworkerimportaynsc_,sleepdeflong_work(t):sleep(t)return"Finished in{}second(s)".format(t)# The async task will be executed in another thread.pending=async_(long_work,5)# Do other stuff here...# Wait the thread to complete and get the result. If the task is already# finished, it returns directly with the result.print(pending.get())Use Channel to broadcast events:#! python3fromworkerimportWorker,Channelchannel=Channel()defcreate_printer(name):printer=Worker()@printer.listen("PRINT")def_(event):print(name,"recieved",event.data)channel.sub(printer)printer.start()returnprinterfoo=create_printer("foo")bar=create_printer("bar")channel.pub("PRINT","Hello channel!")foo.stop()bar.stop()Child thread and event bubbling/broadcasting:#! python3fromworkerimportWorker,sleepdefcreate_thread(name,parent):thread=Worker(parent=parent)@thread.listen("HELLO")def_(event):print(name)returnthread.start()parent=create_thread("parent",None)child=create_thread("child",parent)grand=create_thread("grand",child)# broadcast/bubble is happened in main thread. It doesn't gaurantee the# execution order of listeners.parent.fire("HELLO",broadcast=True)sleep(1)grand.fire("HELLO",bubble=True)sleep(1)# stop a parent thread would also stop its childrenparent.stop()How it worksThe module creates a event queue for each thread, including the main thread. When blocking functions are called (worker.sleep,worker.wait_event,worker.Async.get, etc), they enter the event loop so the thread can process events, communicate with other threads, or raise an exception during the call.Which also means that if you don’t use functions provided by pyThreadWorker, the module has no chance to affect your existing code. It should be easy to work with other frameworks.API referencehttp://pythreadworker.readthedocs.io/en/latest/NotesThread safe operations:http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htmChangelog0.10.0 (Apr 19, 2022)Change: require python 3.10+.Change: now callingwait_*functions would initiate a root worker if there is no worker on the current thread.0.9.0 (Jun 8, 2018)Change: The signature of `later()` is changed. You should use it to schedule a task on the specific thread.Change: The listener registered by `listener()` shortcut would be removed once the thread is stopped.Add:permanentandoncearguments toListener.Add:Defer. A util to handle cross thread communication.0.8.0 (Mar 26, 2017)Add print_traceback option to Worker.Ability to uselateras decorator.Drop __all__ in __init__.py.function rename: async -> async_, sync -> await_.Async now extends Worker and needs start() to run.later() now doesn’t use current thread as target by default. To use current thread as target, pass target=True.Various function are able to used as decorator, includingawait_, async_, later.Drop daemon Thread, use daemon Worker.AddWorker.wait_until.Addcreate_worker.Refactor.0.7.0 (Feb 26, 2017)Improve docs.Dropdef target(thread)syntax, usecurrent()to get current thread instead.Use pylint and sphinx.Exportmore shortcuts.0.6.0 (Jul 1, 2016)Addthread.later.0.5.1 (Apr 22, 2016)Use float in sleep function.0.5.0 (Apr 22, 2016)Add sync.0.4.0 (Apr 20, 2016)breaking changeInterface completely changedDropMessage.put, .getDropUserWorkerDropWorker.create_child. Useparentoption in constructor instead.Dropglobal_cleanupAddsleepAddcurrentAddChannelAddListener.priorityAdddaemonoption toWorkerWorker.cleanup–>Worker.updateWorker.message–>Worker.fireWorker.wait_message–>Worker.wait_eventWorker.message_loop–>Worker.wait_forever0.3.0 (Jun 14, 2015)Catch BaseException.