File: patcher_threading_subclass_done.py

package info (click to toggle)
python-eventlet 0.40.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,200 kB
  • sloc: python: 25,101; sh: 78; makefile: 31
file content (40 lines) | stat: -rw-r--r-- 876 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import queue
import threading


class Worker(threading.Thread):
    EXIT_SENTINEL = object()

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.q = queue.Queue(maxsize=-1)
        self.daemon = True

    def run(self):
        while True:
            task = self.q.get()
            if task == self.EXIT_SENTINEL:
                break
            print(f"Treating task {task}")
            # Pretend to work

    def submit(self, job):
        self.q.put(job)

    def terminate(self):
        self.q.put(self.EXIT_SENTINEL)
        self.join()


if __name__ == "__main__":
    import eventlet
    eventlet.patcher.monkey_patch()

    worker = Worker()
    assert not worker.is_alive()
    worker.start()
    assert worker.is_alive()
    worker.submit(1)
    worker.terminate()
    assert not worker.is_alive()
    print("pass")