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
91
92
93
import threading
import time

class workerThread(threading.Thread):
    def __init__(self):
        self.l = threading.Lock()
        self.workque = []
        threading.Thread.__init__(self)
    
    def run(self):
        while(True):
            self.l.acquire()
            if len(self.workque) == 0:
                self.l.release()
                time.sleep(0.001)
                continue
            
            if self.workque[0] == "exit":
                self.l.release()
                break
            else:
                w = self.workque[0]
                self.workque = self.workque[1:]
                self.l.release()
                exec(w)
                    
    def appendTask(self, task):
        self.l.acquire()
        self.workque.append(task)
        self.l.release()

class threadPool(threading.Thread):
    def __init__(self, n):
        self.l = threading.Lock()
        self.task = []
        self.w = []
        self.isExit = False
        for i in xrange(n):
            self.w.append(workerThread())
            self.w[-1].start()
        threading.Thread.__init__(self)


    def run(self):
        while(True):
            self.l.acquire()
            
            if len(self.task) == 0:
                self.l.release()
                if self.isExit:
                    break
                time.sleep(0.001)
                continue

            isAppend = False
            for w in self.w:
                if len(w.workque) == 0:
                    isAppend = True
                    w.appendTask(self.task[0])
                    self.task = self.task[1:]
                    self.l.release()
                    break

            if isAppend == False:
                self.l.release()
                time.sleep(0.001)

        for w in self.w:
            w.appendTask("exit")
        for w in self.w:
            w.join()

    def appendTask(self, task):
        self.l.acquire()
        self.task.append(task)
        self.l.release()
        
    def exit(self):
        self.l.acquire()
        self.isExit = True
        self.l.release()

tp = threadPool(2)
tp.start()

tp.appendTask("print 'hello world'")
time.sleep(1)
tp.appendTask("print 'sleeping...'\ntime.sleep(10)\nprint 'wake up!'")
tp.appendTask("print 'sleeping...'\ntime.sleep(10)\nprint 'wake up!'")

time.sleep(1)
tp.exit()
tp.join()