Skip to content

Commit 6795ed3

Browse files
authored
Merge pull request #46 from snowyu/master
fix: RuntimeError: can't start new thread
2 parents ce15d1c + 48d63fa commit 6795ed3

File tree

2 files changed

+65
-7
lines changed

2 files changed

+65
-7
lines changed

python/plugins/dotpy.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import re
77
import db
88
import threading
9+
from .threads import ThreadPool
910

1011
class Source (object) :
1112

@@ -18,19 +19,22 @@ def getSource (self) :
1819
with open(sourcePath, 'r') as f:
1920
lines = f.readlines()
2021
total = len(lines)
21-
threads = []
22+
threads = ThreadPool(20)
2223

2324
for i in range(0, total):
2425
line = lines[i].strip('\n')
2526
item = line.split(',', 1)
26-
thread = threading.Thread(target = self.detectData, args = (item[0], item[1], ), daemon = True)
27-
thread.start()
28-
threads.append(thread)
27+
threads.add_task(self.detectData, title = item[0], url = item[1])
28+
# thread = threading.Thread(target = self.detectData, args = (item[0], item[1], ), daemon = True)
29+
# thread.start()
30+
# threads.append(thread)
31+
threads.wait_completion()
2932

30-
for t in threads:
31-
t.join()
33+
# for t in threads:
34+
# t.join()
3235

3336
def detectData (self, title, url) :
37+
print('detectData', title, url)
3438
info = self.T.fmtTitle(title)
3539

3640
netstat = self.T.chkPlayable(url)
@@ -62,4 +66,4 @@ def addData (self, data) :
6266
DB.insert(data)
6367
else :
6468
id = result[0][0]
65-
DB.edit(id, data)
69+
DB.edit(id, data)

python/plugins/threads.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
from queue import Queue
2+
from threading import Thread
3+
4+
5+
class Worker(Thread):
6+
"""Thread executing tasks from a given tasks queue"""
7+
def __init__(self, tasks):
8+
Thread.__init__(self)
9+
self.tasks = tasks
10+
self.daemon = True
11+
self.start()
12+
13+
def run(self):
14+
while True:
15+
func, args, kargs = self.tasks.get()
16+
try:
17+
func(*args, **kargs)
18+
except Exception as e:
19+
print(e)
20+
finally:
21+
self.tasks.task_done()
22+
23+
24+
class ThreadPool:
25+
"""Pool of threads consuming tasks from a queue"""
26+
def __init__(self, num_threads):
27+
self.tasks = Queue(num_threads)
28+
for _ in range(num_threads):
29+
Worker(self.tasks)
30+
31+
def add_task(self, func, *args, **kargs):
32+
"""Add a task to the queue"""
33+
self.tasks.put((func, args, kargs))
34+
35+
def wait_completion(self):
36+
"""Wait for completion of all the tasks in the queue"""
37+
self.tasks.join()
38+
39+
# if __name__ == '__main__':
40+
# from random import randrange
41+
# from time import sleep
42+
43+
# delays = [randrange(1, 10) for i in range(100)]
44+
45+
# def wait_delay(d):
46+
# print 'sleeping for (%d)sec' % d
47+
# sleep(d)
48+
49+
# pool = ThreadPool(20)
50+
51+
# for i, d in enumerate(delays):
52+
# pool.add_task(wait_delay, d)
53+
54+
# pool.wait_completion()

0 commit comments

Comments
 (0)