以下是我的多处理代码。regressTuple 有大约 2000 个项目。因此,以下代码创建了大约 2000 个并行进程。运行此程序时,我的 Dell XPS 15 笔记本电脑崩溃了。
特此我的代码:
regressTuple = [(x,) for x in regressList]
processes = []
for i in range(len(regressList)):
processes.append(Process(target=runRegressWriteStatus,args=regressTuple[i]))
for process in processes:
process.start()
for process in processes:
process.join()
Run Code Online (Sandbox Code Playgroud) python multithreading multiprocessing python-multithreading python-3.x
我正在尝试从另一个 threading.Thread 设置我的 QAbstractTableModel (连接到 QTableView)的 Data() 。模型中的数据按预期更改,但视图不会自行更新(仅在单击激发视图更新的表视图后)。实施此类更新的最佳方式是什么?
我正在使用 pyqt 5.11.1 开发 Python 3.6。我尝试从模型的 setData 方法发出 dataChanged (以及 layoutAboutToBeChanged、layoutChanged、editCompleted)信号 - 这些都不起作用。然后我想出了两种可能的解决方案 -
这两者都按预期工作,但我认为这并不是真正好的解决方案,因为首先更新整个表(我相信是这样),而且这不是真正健康的用例?除了显示数据的一些延迟之外,第二种解决方案只会给应用程序带来恒定的负载。
这是我的问题的最小(希望如此)可重现的例子
import sys
import threading
import time
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt as Qt
class CopterDataModel(QtCore.QAbstractTableModel):
def __init__(self, parent=None):
super(CopterDataModel, self).__init__(parent)
self.data_contents = [[1, 2]]
def rowCount(self, n=None):
return len(self.data_contents)
def columnCount(self, n=None):
return 2
def data(self, index, role):
row = index.row() …Run Code Online (Sandbox Code Playgroud) 使用 ThreadPoolExecutor 上的 python 文档有这个请求函数:
import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
'http://www.cnn.com/',
'http://europe.wsj.com/',
'http://www.bbc.co.uk/',
'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
with urllib.request.urlopen(url, timeout=timeout) as conn:
return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
# Start the load operations and mark each future with its URL
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in …Run Code Online (Sandbox Code Playgroud) 使用时ThreadPoolExecutor如何在信号中断时优雅退出?我想拦截 SIGINT 并优雅地退出该进程。我希望当前正在运行的线程完成,但不再启动,并取消所有挂起的任务。
就目前而言,我已经找到了很多关于 contextvars 模块如何与 asyncio 一起运行的示例,但没有一个关于如何与线程一起运行的示例(asyncio.get_event_loop().run_in_executor、threading.Thread 等)。
我的问题是,如何将上下文传递给单独的线程?下面您可以看到一个不起作用的代码片段(python 3.9.8)。
import typing
import asyncio
import contextvars
import concurrent.futures
class CustomThreadPoolExecutor(concurrent.futures.ThreadPoolExecutor):
def submit(
self,
function: typing.Callable,
*args,
**kwargs
) -> concurrent.futures.Future:
context = contextvars.copy_context()
return super().submit(
context.run,
functools.partial(function, *args, **kwargs)
)
def function():
print(var.get())
async def main():
await asyncio.get_event_loop().run_in_executor(None, function)
if __name__ == '__main__':
var = contextvars.ContextVar('variable')
var.set('Message.')
asyncio.get_event_loop().set_default_executor(CustomThreadPoolExecutor)
asyncio.run(main())
Run Code Online (Sandbox Code Playgroud) asyncio我第一次尝试理解这一点,我想我已经基本掌握了协程以及如何等待其相应的对象。现在,我遇到了AbstractEventLoop.run_in_executor,这个概念在抽象中是有意义的(没有双关语):你有一些阻塞操作,所以你将它启动到一个线程,以便主线程(即运行主事件循环的线程)可以继续其工作。
我不明白的是事件循环如何管理协程(协作多任务处理)和这个新创建的线程(抢占式多任务处理)之间的上下文切换。据我了解,每个协程都是awaited 的,并且await该协程的行为将控制权交还给事件循环。这允许事件循环开始运行另一个协程。但线程不是以这种方式合作的——还有一些其他调度程序(我相信在你的操作系统中,但这可能是错误的)在线程运行时进行调度,并且线程可以在执行过程中的任何时候停止。此外,为什么还要调用run_in_executor事件循环?为了实现我们正在寻找的并发性,新创建的线程是否应该与运行事件循环的线程完全分开?
我对可能发生的情况的唯一猜测是,由于run_in_executor返回了一个协程(这也有点令人困惑 - 如何从线程中获取协程?),awaiting 这个协程会导致底层线程中的上下文切换,但我真的不知道如何实现这样的事情。
from concurrent.futures import ThreadPoolExecutor, as_completed
def main():
with ThreadPoolExecutor(max_workers=16) as producersPool:
for i in [1,2,3,4,5,6,7,8,9,0]:
producersPool.submit((lambda i : print(i))(i))
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
使用python3运行:
1
2
3
4
5
6
7
8
9
0
Run Code Online (Sandbox Code Playgroud)
总是一样.
现在我希望你让我正确 - 我不一定希望重新安排这些任务,但我只是想知道为什么排序会发生?我的意思是,人们可以期望在一个线程内以确定的方式完成任务,但线程的严格排队对我来说似乎有些奇怪.
无论如何,我如何在Python 3中获得真正的并发?(据我所知,Jython和IronPython只支持2.x).
我想使用multiprocessing.Pool,但是multiprocessing.Pool不能在超时后中止任务。我找到了解决方案,并对其进行了一些修改。
from multiprocessing import util, Pool, TimeoutError
from multiprocessing.dummy import Pool as ThreadPool
import threading
import sys
from functools import partial
import time
def worker(y):
print("worker sleep {} sec, thread: {}".format(y, threading.current_thread()))
start = time.time()
while True:
if time.time() - start >= y:
break
time.sleep(0.5)
# show work progress
print(y)
return y
def collect_my_result(result):
print("Got result {}".format(result))
def abortable_worker(func, *args, **kwargs):
timeout = kwargs.get('timeout', None)
p = ThreadPool(1)
res = p.apply_async(func, args=args)
try:
# Wait timeout …Run Code Online (Sandbox Code Playgroud) python multithreading multiprocessing python-multithreading python-multiprocessing
我对使用“ concurrent.futures”进行并行处理还很陌生,并且正在测试一些简单的实验。我编写的代码似乎有效,但是我不确定如何存储结果。我试图创建一个列表(“ futures”)并将结果附加到该列表中,但这会大大减慢该过程。我想知道是否有更好的方法可以做到这一点。谢谢。
import concurrent.futures
import time
couple_ods= []
futures=[]
dtab={}
for i in range(100):
for j in range(100):
dtab[i,j]=i+j/2
couple_ods.append((i,j))
avg_speed=100
def task(i):
origin=i[0]
destination=i[1]
time.sleep(0.01)
distance=dtab[origin,destination]/avg_speed
return distance
start1=time.time()
def main():
with concurrent.futures.ThreadPoolExecutor() as executor:
for number in couple_ods:
future=executor.submit(task,number)
futures.append(future.result())
if __name__ == '__main__':
main()
end1=time.time()
Run Code Online (Sandbox Code Playgroud) 我正在Python / Flask中实现GUI。设计烧瓶的方式中,必须“手动”打开本地主机以及端口号。
有没有一种方法可以使它自动化,以便在运行代码时自动打开浏览器(本地主机)?
我尝试使用webbrowser软件包,但在会话被杀死后会打开网页。
我还查看了以下帖子,但它们让我头疼。
当基于用户输入呈现html页面时,会发生问题。
提前致谢。
import webbrowser
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
webbrowser.open_new('http://127.0.0.1:2000/')
app.run(port=2000)
Run Code Online (Sandbox Code Playgroud)