我有一个简单的多线程代码,其中一些线程将项放入队列,一些线程从队列中获取项: https://repl.it/@chuoi123/simpleThreading
如果您不想访问上面的链接,请输入完整代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
train_errors = [1,2,3,4,5]
val_errors = [2,1,4,2,3]
test_errors = [5,4,3,2,1]
X = list("ABCDE")
x1 = [i-0.2 for i in range(len(train_errors))]
x2 = [i for i in range(len(train_errors))]
x3 = [i+0.2 for i in range(len(train_errors))]
ax.bar(x1, train_errors, width=0.2, color='b', label="Train Errors")
ax.bar(x2, val_errors, width=0.2, color='g', label="Val Errors")
ax.bar(x3, test_errors, width=0.2, color='r', label="Test Errors")
ax.set_xticks(x2)
ax.set_xticklabels(X)
ax.legend()
ax.set_xlabel('Models')
ax.set_ylabel('RMSE')
ax.set_title('Regression Models Comparison')
plt.show()
我的问题是放线程并且线程不会同时运行,因此一种类型在代码中以其顺序运行。当前代码的结果:
import threading
import queue
import time
def PutWorker(maxValue):
global item
while True:
with putLock:
if item > maxValue:
break
q.put(item)
print('Added item ' + str(item))
item += 1
time.sleep(0.5)
def GetWorker():
while True:
item = q.get()
if item is None:
break
with getLock:
print('Deleted item ' + str(item))
q.task_done()
time.sleep(1)
## main process from here
q = queue.Queue()
threads = []
putLock = threading.Lock()
getLock = threading.Lock()
item = 1
while True:
try:
numValue = int(input('Number of items in queue: '))
numThreadsGet = int(input('Number of getting threads: '))
numThreadsPut = int(input('Number of putting threads: '))
break
except:
print('Input must be ingeter.')
for i in range(numThreadsPut):
t = threading.Thread(target=PutWorker(numValue),daemon = True)
t.start()
threads.append(t)
for i in range(numThreadsGet):
t = threading.Thread(target=GetWorker,daemon = True)
t.start()
threads.append(t)
我想要这样的结果:
Added item 1
Added item 2
Added item 3
Added item 4
Added item 5
...
Deleted item 1
Deleted item 2
Deleted item 3
Deleted item 4
Deleted item 5
...
为什么会发生这种情况以及我可以做些什么来归档我的目标?
编辑:在@ user68014的答案中尝试解决方案之后,我发现另一种方法是从Added item 1
Added item 2
Deleted item 1
Added item 3
Deleted item 2
Added item 4
Deleted item 3
Added item 5
Deleted item 4
Deleted item 5
...
删除参数,并使用全局变量简单地使用def PutWorker()
。
答案 0 :(得分:1)
问题在于这一行:
t = threading.Thread(target=PutWorker(numValue),daemon = True)
您实际上调用 PutWorker将目标移至Thread。所以在实际创建线程之前都会发生这种情况。你应该传递函数本身。
类似于:
t = threading.Thread(target=PutWorker, ...
没有参数,没有调用,它只是一个函数(Thread会调用它来启动线程)
由于它有一个参数,你需要" Curry"那个。我这样做:
from functools import partial
...
t = threading.Thread(target=partial(PutWorker, numValue), ...