forked from Legal-NLP-EkStep/rhetorical-role-baseline
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgpu_executor.py
More file actions
53 lines (39 loc) · 1.21 KB
/
gpu_executor.py
File metadata and controls
53 lines (39 loc) · 1.21 KB
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
from queue import Queue
from threading import Thread
import time
class GPUWorker(Thread):
def __init__(self, gpu, queue):
Thread.__init__(self)
self.gpu = gpu
self.queue = queue
self.setName(f'GPU {self.gpu} worker')
def run(self):
print(f'Started thread: {self.getName()}')
while True:
func = self.queue.get()
if func is None:
break
func(self.gpu)
self.queue.task_done()
print(f'Shutdown thread: {self.getName()}')
class GPUExecutor:
def __init__(self, gpus):
self.gpus = gpus
self.queue = Queue()
self.workers = []
for gpu in self.gpus:
worker = GPUWorker(gpu=gpu, queue=self.queue)
self.workers.append(worker)
worker.start()
def submit(self, func):
"""func: lambda getting gpu-num as argument. """
self.queue.put(func)
def shutdown(self):
print(f'Shutdown...')
self.queue.join()
for _ in self.workers:
self.queue.put(None)
for w in self.workers:
print(f'Joining thread {w.getName()}...')
w.join()
print(f'Shutdown finished!')