我试图在多线程程序中将信号从子线程发送到主线程(不能使用多进程)。不幸的是,即使在用尽所有在线可用的阅读材料(我可以找到)之后,我也无法清楚地了解如何这样做。我是信号和python的初学者,所以请耐心等待并像对新手一样解释。我不能在进程中使用 join 方法,因为我希望两个线程同时运行。这是我在这里找到的与该主题相关的代码 - http://pymotw.com/2/signal/#signals-and-threads ,它对我来说并不真正有效。
import signal
import threading
import os
import time
def signal_handler(num, stack):
print 'Received signal %d in %s' % (num, threading.currentThread())
signal.signal(signal.SIGUSR1, signal_handler)
def wait_for_signal():
print 'Waiting for signal in', threading.currentThread()
signal.pause()
print 'Done waiting'
# Start a thread that will not receive the signal
receiver = threading.Thread(target=wait_for_signal, name='receiver')
receiver.start()
time.sleep(0.1)
def send_signal():
print 'Sending signal in', threading.currentThread()
os.kill(os.getpid(), signal.SIGUSR1)
sender = threading.Thread(target=send_signal, name='sender')
sender.start()
sender.join()
# Wait for the thread to see the signal …Run Code Online (Sandbox Code Playgroud) 我有 Thread,我想在它完成时更改一些标志。例如:
import threading
def on_done():
# do some printing or change some flags
def worker():
# do some calculations
t = threading.Thread(target=worker, on_close=on_done)
t.start()
Run Code Online (Sandbox Code Playgroud)
但我无法找到这样的方法。任何想法我怎么能以某种方式管理它?工作函数在单独的文件中,所以它不知道关于标志。
提前谢谢
python 的多处理队列的文档:https : //docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue
不像 queue.Queue 那样清楚:https ://docs.python.org/3/library/queue.html
当 maxsize 参数没有提供给构造函数时,关于队列的大小是否是“无限的”(例如,在程序可以设法分配内存的任何可能范围内)。
是这样吗?
python python-multithreading python-3.x python-multiprocessing python-3.6
我想命名 a 中的线程multiprocessing.dummy.Pool,以便当我threading.enumerate()从主线程调用时可以查看它们的所有名称。pool.apply_async当我调用能够命名线程时,是否可以应用关键字?我宁愿在创建时命名它们,而不是在tester函数内部命名,只是为了简洁。
例如,如果我有下面的示例代码:
import multiprocessing.dummy
from time import sleep
import threading
def tester():
sleep(2)
print("running \n")
def run_conc(number_of_threads, fxn):
pool = multiprocessing.dummy.Pool(processes=number_of_threads)
for thread in range(number_of_threads):
pool.apply_async(tester)
print(threading.enumerate(), "\n")
pool.close()
pool.join()
run_conc(3, tester)
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我收到输出:
[<_MainThread(MainThread, started 140735632434048)>, <Thread(SockThread, started daemon 123145521917952)>, <DummyProcess(Thread-1, started daemon 123145527246848)>, <DummyProcess(Thread-2, started daemon 123145532502016)>, <DummyProcess(Thread-3, started daemon 123145537757184)>, <Thread(Thread-4, started daemon 123145543012352)>, <Thread(Thread-5, started daemon 123145548267520)>, <Thread(Thread-6, started daemon 123145553522688)>]
running
running
running
Run Code Online (Sandbox Code Playgroud)
我希望能够命名该线程列表中的 3 个虚拟线程,以便我可以识别哪个是哪个。或者也许有一种方法可以从内部做到这一点 …
我对 Python 还很陌生。我正在尝试使用threading模块。我遇到了Event物体。
事件对象具有
wait
set
clear
函数。我明白 wait、set 和clear 正在做什么。但我不太明白为什么有一个单独的明确方法。难道不能将其包含在 set 方法实现中吗?
到目前为止我看到的大多数代码都是set方法后面跟着一个clear方法。以便后续的wait方法调用wait。
我来自 Java 世界,我忍不住将其与 wait 和 notification 方法调用进行比较。需要明确的是,Java 中没有等效的方法调用。
是否存在使用 set 但不明确方法的用例?
我正在使用具有多个线程的多个解释器,并且我尝试使用它PyThreadState_SetAsyncExc来停止脚本,但它没有效果:
void stop()
{
PyThreadState *ts = PyThreadState_Swap(this->tstate);
PyObject *exc = PyObject_CallObject(PyExc_Exception, Py_BuildValue("(s)", "stopped"));
int n = PyThreadState_SetAsyncExc(this->tstate->thread_id, exc);
if(n < 1)
std::cerr << "Script::stop: thread not found!" << std::endl;
PyThreadState_Swap(ts);
}
Run Code Online (Sandbox Code Playgroud)
返回值为1,但线程继续运行。为什么?
完整的测试用例:
#include <Python.h>
#include <iostream>
#include <thread>
using namespace std::chrono_literals;
struct Script
{
Script()
{
PyThreadState *ts = PyThreadState_Get();
this->tstate = Py_NewInterpreter();
PyThreadState_Swap(ts);
}
virtual ~Script()
{
if(!this->tstate) return;
PyThreadState *ts = PyThreadState_Swap(this->tstate);
Py_EndInterpreter(this->tstate);
PyThreadState_Swap(ts);
}
void run(const char *code)
{
PyThreadState *ts = PyThreadState_Swap(this->tstate); …Run Code Online (Sandbox Code Playgroud) 我正在尝试将一些鼠标自动移动到 Python 3 中的某个位置。为此,我使用 module pyclicker,特别HumanClicker是模块中的类。它使用一种算法来计算鼠标移动的“类似人类”的点流。为了实际沿着它使用的计算点移动它pyautogui.moveTo(). From pyclicker.HumanClicker:
def move(self, toPoint, duration=2, humanCurve=None):
fromPoint = pyautogui.position()
if not humanCurve:
humanCurve = HumanCurve(fromPoint, toPoint)
pyautogui.PAUSE = duration / len(humanCurve.points)
for point in humanCurve.points:
pyautogui.moveTo(point)
Run Code Online (Sandbox Code Playgroud)
通过移动鼠标和加速/减速,我得到了一些非常好的结果,但是使用 pyautogui 移动鼠标(因此也使用这个 HumanClicker)会锁定程序,直到它完成移动。为了解决这个问题,我在需要时将鼠标移动的处理放入单独的线程中。我的调用代码move():
def move(self, location, time):
try:
hc = HumanClicker()
hc.move(location, time)
except TypeError:
pass
Run Code Online (Sandbox Code Playgroud)
其中位置是浮点数(x, y) tuple,时间是浮点数(当前为 0.2)。对运动进行线程化是可行的,但它会显着减慢运动速度并使其更加不稳定/卡顿(两者都随着运动距离的增加而呈指数级增长)。以任何方式对其进行线程化都会得到相同的结果。如果需要,我可以提供运动记录。
这种互动减慢/卡顿有什么具体原因吗?
是否有一个模块可以替换 pyautogui 以使其在线程中不会出现这些问题?
或者还有其他方法可以解决这个问题吗?
我试图找出 psycopg2 连接池之间的SimpleConnectionPool区别ThreadedConnectionPool。
该文档说:
SimpleConnectionPool连接只能在单线程应用程序/脚本内使用。
ThreadedConnectionPool连接可以在多线程应用程序/脚本中安全地使用。
这里是什么safely意思?
我的理解/困惑:
"""
eg1: Simple Connection Pooling example
"""
from psycopg2.pool
from concurrent.futures
def someTask(id):
# CRUD queries to Postgres, that I will be multithreading
print(f"Thread: {id}")
conn = simple_pool.getconn()
# do DB operation
simple_pool = psycopg2.pool.SimpleConnectionPool(10, 15, #DB Info)
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
executor.map(someTask, range(1,10))
Run Code Online (Sandbox Code Playgroud)
"""
eg2: Threaded Connection Pooling example
"""
from psycopg2.pool
from concurrent.futures
def someTask(id):
# CRUD queries to …Run Code Online (Sandbox Code Playgroud) 我有一个在多线程环境中使用的 asyncio gRPC 客户端。当多个线程同时通过客户端连接到服务时,我看到以下错误流:
2021-01-27 09:33:56,937 错误 [asyncio] [thread_0] 回调 PollerCompletionQueue._handle_events()() 中出现异常
处理: )()>
回溯(最近一次调用最后一次):
文件“/usr/local/lib/python3.8/asyncio/events.py”,第 81 行,在 _run 中
self._context.run(self._callback, *self._args)
文件“src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi”,第 147 行,位于 grpc._cython.cygrpc.PollerCompletionQueue._handle_events 中
BlockingIOError:[Errno 11] 资源暂时不可用
2021-01-27 09:33:56,937 错误 [asyncio] [thread_1] 回调 PollerCompletionQueue._handle_events()() 中出现异常
处理: )()>
回溯(最近一次调用最后一次):
文件“/usr/local/lib/python3.8/asyncio/events.py”,第 81 行,在 _run 中
self._context.run(self._callback, *self._args)
文件“src/python/grpcio/grpc/_cython/_cygrpc/aio/completion_queue.pyx.pxi”,第 147 行,位于 grpc._cython.cygrpc.PollerCompletionQueue._handle_events 中
BlockingIOError:[Errno 11] 资源暂时不可用
这些请求似乎已成功完成,但是,这些消息充斥着我的日志,让我感到紧张!
在我的测试中,每个线程创建自己的通道并提交自己的异步请求。无论服务负载如何,都会发生错误。如果客户端在不同进程中运行,则不会发生错误。
我的设置:
3.8.6grpcio版本:1.35.0任何见解表示赞赏!
python python-multithreading python-asyncio grpc grpc-python
我将 FastAPI 用于生产应用程序,该应用程序几乎完全使用 asyncio,除非访问数据库。该数据库仍然依赖于同步 SQLAlchemy,因为异步版本当时仍处于 alpha(或早期 beta)状态。
虽然我们的服务最终会在访问数据库时进行同步阻塞调用,但它仍然包含在异步函数中。我们确实运行了多个工作进程和应用程序的多个实例,以确保我们不会遇到严重的瓶颈。
我知道 FastAPI 在使用该def controller_method方法时使用线程提供并发性,但我似乎找不到有关它如何控制环境的任何细节。有人可以帮助我了解如何控制进程可以生成的最大线程数。如果达到系统限制怎么办?
当我使用异步等待模型时,我在中间件中创建数据库连接对象,并将其注入到控制器操作中。
@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
await _set_request_id()
try:
request.state.db = get_sessionmaker(scope_func=None)
response = await call_next(request)
finally:
if request.state.db.is_active:
request.state.db.close()
return response
Run Code Online (Sandbox Code Playgroud)
当通过线程完成时,控制器是否已经在单独的线程中调用,确保每个请求都有单独的连接?
现在,如果我无法限制主进程生成的线程数量,如果我的应用程序突然收到大量请求,它是否会超出数据库连接池限制并最终阻止我的应用程序?
FastAPI 是否有一个可以配置的中央线程池,或者是由 Uvicorn 控制的?
我看到 Uvicorn 有一个配置,可以使用该--limit-concurrency 60标志来限制并发性。这是控制在线程模式下创建的并发线程的数量吗?
如果是这样,这是否应该始终低于我的连接池(连接池 + max_overflow=40)
那么在这种情况下,我允许 uvicorn 并发限制为 60,我的数据库连接池配置应该是这样的?
engine = sqlalchemy.create_engine(
cfg("DB_URL"),
pool_size=40,
max_overflow=20,
echo=False,
pool_use_lifo=False,
pool_recycle=120
)
Run Code Online (Sandbox Code Playgroud)
在这种情况下是否使用了中央线程池?是否有任何示例项目可供我查看,以了解在大规模部署时如何配置。
我使用 Netflix Dispatch 作为参考,但如果还有其他项目,我肯定想看看。
python ×8
python-3.x ×4
callback ×1
fastapi ×1
grpc ×1
grpc-python ×1
mouse ×1
psycopg2 ×1
pyautogui ×1
python-2.7 ×1
python-3.6 ×1
python-c-api ×1
signals ×1