我正在浏览信号量小册子"现在,我遇到了第一个障碍问题。在下面的代码中,我尝试在继续之前有3个线程集合点。这部分工作正常 - 我总是得到3"在推送到队列之前。但是,在推送到队列之后,我并不总是得到3"有时候我会,但并非总是这样。我做错了什么?
import threading
import random
import Queue
import time
num_loops = 1
class myThread(threading.Thread):
def __init__(self, id, count, n, q, locks):
threading.Thread.__init__(self)
self.id = id
self.q = q
self.n = n
self.locks = locks
self.count = count
return
def run(self):
time.sleep(random.random()/100)
self.q.put("before")
with self.locks['mutex']:
self.count[0] += 1
if self.count[0] == self.n:
locks['barrier'].release()
locks['barrier'].acquire()
locks['barrier'].release()
time.sleep(random.random()/100)
self.q.put("after")
if __name__ == '__main__':
total = 10
incorrect = 0
num_threads = 3
for _ in range(total):
q = Queue.Queue()
locks = {'mutex': threading.Semaphore(1),
'barrier': threading.Semaphore(0),
}
threads = []
count = [0]
for i in range(num_threads):
t = myThread(i, count, num_threads, q, locks)
t.start()
threads.append(t)
for i in threads:
t.join()
print "join"
one_loop = ['before']*num_threads + ['after']*num_threads
total_loop = one_loop * num_loops
result = []
while not q.empty():
result.append(q.get())
print result
if result != total_loop:
incorrect += 1
print "%s out of %s is wrong" % (incorrect, total)
答案 0 :(得分:1)
我发现了问题。你没有加入所有的线程。这一行:
for i in threads:
t.join()
print "join"
应该是:
for i in threads:
i.join() # changed line
print "join"
加入t
首先只是等待创建的最后一个线程,然后在其余的迭代中等待无操作。