Python - How can I implement a 'stoppable' thread?

前端 未结 3 1492
梦毁少年i
梦毁少年i 2020-12-21 07:21

There is a solution posted here to create a stoppable thread. However, I am having some problems understanding how to implement this solution.

Using the code...

3条回答
  •  爱一瞬间的悲伤
    2020-12-21 08:22

    Inspired by above solution I created a small library, ants, for this problem.

    Example

    from ants import worker
    
    @worker
    def do_stuff():
        ...
        thread code
        ...
    
    do_stuff.start()
    ...
    do_stuff.stop()
    

    In above example do_stuff will run in a separate thread being called in a while 1: loop

    You can also have triggering events , e.g. in above replace do_stuff.start() with do_stuff.start(lambda: time.sleep(5)) and you will have it trigger every 5:th second

    The library is very new and work is ongoing on GitHub https://github.com/fa1k3n/ants.git

提交回复
热议问题