我想让一个线程等到多线程队列不为空。队列只有一个生产者和一个消费者。生产者在任务可用时将任务放入队列,但生产者必须等到收集到两个或更多任务。我不只是使用该get方法两次来检索两个任务的原因是因为它使算法流程过于复杂。但是,这不能在下面的代码段中描述,因为显然这只是一个过于简单的例子。
我需要知道队列不是空的,以便我可以将队列的峰值(不删除它)与我刚刚删除的元素进行比较 get
如何通过睡眠来完成:
while myQueue.empty():
sleep(0.05)
Run Code Online (Sandbox Code Playgroud)
如何在不使用睡眠的情况下做到这一点?我应该使用event.wait()吗?如果是,我无法弄清楚应该如何正确使用该event.clear()命令。由于我想要等待的线程也是消费者,我无法确定队列是否为空。即使我queue.empty()用来检查。
尽管保存了对QThreadas的引用,但self.lightsThread停止QObject self.lightsWorker然后self.lightsThread再次启动会导致错误
QThread: Destroyed while thread is still running
Run Code Online (Sandbox Code Playgroud)
停止后self.lightsWorker,也必须QThread self.lightsThread停止吗?如果没有,似乎是什么问题?
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import time
class Screen(QMainWindow):
def __init__(self):
super(Screen, self).__init__()
self.initUI()
def initUI(self):
self.lightsBtn = QPushButton('Turn On')
self.lightsBtn.setCheckable(True)
self.lightsBtn.setStyleSheet("QPushButton:checked {color: white; background-color: green;}")
self.lightsBtn.clicked.connect(self.lightsBtnHandler)
self.setCentralWidget(self.lightsBtn)
def lightsBtnHandler(self):
if self.lightsBtn.isChecked():
self.startLightsThread()
else:
self.stopLightsThread()
def startLightsThread(self):
print 'start lightsThread'
self.lightsThread = QThread()
self.lightsWorker = LightsWorker()
self.lightsWorker.moveToThread(self.lightsThread)
self.lightsThread.started.connect(self.lightsWorker.work)
self.lightsThread.start()
def stopLightsThread(self):
print …Run Code Online (Sandbox Code Playgroud) 我在使用Timer线程功能时遇到了困难。
基本上,当我的程序启动时,我想每 x 秒记录一次统计信息。
所以我想我可以用这个Timer函数来做(每 5 秒启动一次函数)。
现在,我做了:
from threading import Timer
def startLogger():
while True:
t = Timer(5, function)
t.start()
def function():
print("hey")
Run Code Online (Sandbox Code Playgroud)
但它启动错误,所以我认为这不是一个好方法。
RuntimeError: can't start new thread
如果有人能给我一个线索,将不胜感激!
好像asyncio.Queue只能由同一个线程推读吗?例如:
import asyncio
from threading import Thread
import time
q = asyncio.Queue()
def produce():
for i in range(100):
q.put_nowait(i)
time.sleep(0.1)
async def consume():
while True:
i = await q.get()
print('consumed', i)
Thread(target=produce).start()
asyncio.get_event_loop().run_until_complete(consume())
Run Code Online (Sandbox Code Playgroud)
只打印
consumed 0
Run Code Online (Sandbox Code Playgroud)
然后挂起。我错过了什么?
python multithreading python-multithreading async-await python-asyncio
I'm trying to cleanly exit after some work times out because a thread is being blocked by something. I'm using a ThreadPoolExecutor like this:
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor:
# submit some work
workers = [executor.submit(...) for x in work]
# wait for completion
try:
for f in concurrent.futures.as_completed(workers, timeout=60):
f.result()
except concurrent.futures.TimeoutError:
raise TimeoutError()
except TimeoutError:
# cleanup
Run Code Online (Sandbox Code Playgroud)
This code gets to # cleanup no problem, but the script never exits because it's waiting for that blocked thread to …
在这段代码中:
import concurrent.futures
import time
def pafter(t):
time.sleep(t)
print('Hi')
with concurrent.futures.ThreadPoolExecutor(5) as e:
e.submit(pafter, 2)
print('With returned')
Run Code Online (Sandbox Code Playgroud)
我希望看到:
With returned
Hi
Run Code Online (Sandbox Code Playgroud)
但我看到:
Hi
With returned
Run Code Online (Sandbox Code Playgroud)
为什么不submit立即返回?我要改变什么才能让它这样做?
在python 2中,multiprocessing.dummy.Pool和之间有什么区别multiprocessing.pool.ThreadPool吗?源代码似乎暗示它们是相同的。
python threadpool python-multithreading python-2.7 python-multiprocessing
为什么下面的代码只适用于multiprocessing.dummy,而不适用于 simple multiprocessing。
import urllib.request
#from multiprocessing.dummy import Pool #this works
from multiprocessing import Pool
urls = ['http://www.python.org', 'http://www.yahoo.com','http://www.scala.org', 'http://www.google.com']
if __name__ == '__main__':
with Pool(5) as p:
results = p.map(urllib.request.urlopen, urls)
Run Code Online (Sandbox Code Playgroud)
错误 :
Traceback (most recent call last):
File "urlthreads.py", line 31, in <module>
results = p.map(urllib.request.urlopen, urls)
File "C:\Users\patri\Anaconda3\lib\multiprocessing\pool.py", line 268, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Users\patri\Anaconda3\lib\multiprocessing\pool.py", line 657, in get
raise self._value
multiprocessing.pool.MaybeEncodingError: Error sending result: '[<http.client.HTTPResponse object at 0x0000016AEF204198>]'. Reason: …Run Code Online (Sandbox Code Playgroud) python urllib multiprocessing python-multithreading python-multiprocessing
我是 Python 的初学者。现在我阅读了有关线程的信息,但我有一些问题。
IMO 原子操作 (AO) = 最简单的操作。dev 中最简单的操作是a = 1. 但是我确实读了这篇文章(http://preshing.com/20130618/atomic-vs-non-atomic-operations/),我的印象是它没有最简单的操作\AO。作者告诉我们这个操作分为两个操作,这个操作不是AO。这个操作是AO,它必须有另一种类型。但我必须说他谈到了 C/C++ 和字节码,我认为在 Python 中也是如此。我如何理解这取决于类型和编译器。但是 Python 是动态类型的语言。它没有类型。
我决定向社区提出以下问题:
Python 中的原子操作是什么?
哪些操作是 Python 中的 AO?
如果简单的操作不简单,那么我不明白什么是原子操作。
我知道使用传统的多处理库我可以声明一个值并在进程之间共享状态。
使用较新的concurrent.futures库时,如何在进程之间共享状态?
import concurrent.futures
def get_user_object(batch):
# do some work
counter = counter + 1
print(counter)
def do_multithreading(batches):
with concurrent.futures.ThreadPoolExecutor(max_workers=25) as executor:
threadingResult = executor.map(get_user_object, batches)
def run():
data_pools = get_data()
start = time.time()
with concurrent.futures.ProcessPoolExecutor(max_workers=PROCESSES) as executor:
processResult = executor.map(do_multithreading, data_pools)
end = time.time()
print("TIME TAKEN:", end - start)
if __name__ == '__main__':
run()
Run Code Online (Sandbox Code Playgroud)
我想保持这个计数器的同步值。
在以前的库中,我可能使用过multiprocessing.Value和Lock.
python python-multithreading python-3.x python-multiprocessing
python ×9
python-2.7 ×2
python-3.x ×2
async-await ×1
concurrency ×1
pyqt ×1
qt ×1
threadpool ×1
timer ×1
urllib ×1