我是线程和排队的新手。下面的函数只接受一个字符串并返回截断的char ex: 789 it returns ['789','89','9']
的列表。但是我得到了奇怪的输出。
def do_stuff(q):
while True:
x=str(q.get())
print [x[i:]for i in range(len(x))]
q.task_done()
q = Queue(maxsize=0)
num_threads = 10
for i in range(num_threads):
worker = threading.Thread(target=do_stuff, args=(q,))
worker.setDaemon(True)
worker.start()
for x in xrange(10,100000):
q.put(x)
q.join()
MyOutput中:
['10', ['0''1]1'[
, '12''1', ]'2'
][
'13'[, '1'43''[, ]'15''4'
, ]['5'
'16'],
'6' ][[
'17''18', , '7''8'[]]'19'
, '9']
['20'[, '21''0'[, ]'22''1'
, ]['2'
'23' ], [
'3''24'][,
'25''4'[, ]'26''5'
, ]['6'
'27'][,
'28''7', ]'8'
][
'29', '9']
['30', '0']
[['31''32', , '1'['2']'33']
,
['3''34'],
'4'[]'35'
, [['5''36''37'], ,
'6''7'][]
'38'
, '8'[]'39
', '9']
['40'[, '41''0', ]'1'
][
'42'[, '43''2'[, ]'44''3'
, ]'4'
]['45'
, '5'[]'46'
, '6'[]'47'
, '7'][
'48', '8']
['49', '9']
['50'[, '51''0'[, ]'52''1'
, ]'2'
]
['53', ['3''54'],
'4'[[]'55''56'
, , '5''6'][]
'57
', '7'] ..... so on
但预期输出:
['10','0']
['11','1']
['12','1'] so on
为什么队列被覆盖?
答案 0 :(得分:0)
问题,因为Dano说线程覆盖了队列。解决它我搜索锁。我找到了方法
queueLock = threading.Lock()
def do_stuff(q):
print threading.current_thread()
while True:
queueLock.acquire()
x=str(q.get())
print [x[i:]for i in range(len(x))]
queueLock.release()
q.task_done()
现在输出
['10', '0']
['11', '1']
['12', '2']
['13', '3']
['14', '4']...
感谢Dano