This repository has been archived by the owner on Mar 25, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
worker.py
90 lines (66 loc) · 1.54 KB
/
worker.py
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
Module for executing tasks in separate thread.
"""
try:
from queue import Queue
except:
# ST2, Python 2
from Queue import Queue
import threading
import traceback
class Worker:
"""
Worker to execute tasks.
"""
def __init__(self):
self.q = Queue()
self.running = False
def start(self):
"""
Starts worker thread.
"""
if not self.running:
self.running = True
threading.Thread(target=self.loop).start()
def stop(self):
"""
Stops worker thread.
"""
self.running = False
self.q.put(lambda: 42) # no-op to unpause thread
def execute(self, callback):
"""
Enqueues task to execute.
"""
self.q.put(callback)
def loop(self):
"""
Thread loop.
"""
while self.running:
try:
callback = self.q.get(block=True)
callback()
except:
print("Error in YAML Nav worker thread:", traceback.format_exc())
# Main worker instance
__worker = None
def execute(callback):
"""
Executes given callback in separate thread.
"""
global __worker
# Create worker on demand
if not __worker:
__worker = Worker()
__worker.start()
__worker.execute(callback)
def unload_handler():
"""
Sublime will call this function on plugin reload.
"""
global __worker
# Stop the worker
if __worker:
__worker.stop()
__worker = None