标签: python-multithreading

Python asyncio run_coroutine_threadsafe 从不运行协程?

我不确定我在这里做错了什么,我试图拥有一个包含队列并使用协程来消耗该队列上的项目的类。问题是事件循环正在一个单独的线程中运行(在该线程中我是为了loop.run_forever()让它运行)。

但我看到的是,用于消费项目的协程从未被触发:

import asyncio
from threading import Thread

import functools

# so print always flushes to stdout
print = functools.partial(print, flush=True)


def start_loop(loop):
    def run_forever(loop):
        print("Setting loop to run forever")
        asyncio.set_event_loop(loop)
        loop.run_forever()
        print("Leaving run forever")

    asyncio.set_event_loop(loop)
    print("Spawaning thread")
    thread = Thread(target=run_forever, args=(loop,))
    thread.start()


class Foo:
    def __init__(self, loop):
        print("in foo init")
        self.queue = asyncio.Queue()
        asyncio.run_coroutine_threadsafe(self.consumer(self.queue), loop)

    async def consumer(self, queue):
        print("In consumer")
        while True:
            message = await queue.get()
            print(f"Got message {message}")
            if message == "END OF QUEUE":
                print(f"exiting …
Run Code Online (Sandbox Code Playgroud)

python python-multithreading python-asyncio

4
推荐指数
1
解决办法
6879
查看次数

Qwidget 背景颜色改变时程序随机崩溃

设置背景颜色很好,但我的界面有一个 Qwidget,它会在某个时刻更改其背景颜色。这将导致程序崩溃,当我注释掉颜色改变代码时崩溃停止。

下面的代码在运行一段时间后肯定会崩溃。

import sys
from PySide2.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,\
QLabel,QMainWindow,QLineEdit,QScrollArea,QVBoxLayout,QMessageBox
from PySide2.QtCore import QTimer,QDateTime,QSize,Qt
from PySide2.QtGui import *
import requests,json
import configparser #
import os
import time
import threading #
from pynput import keyboard #
import requests,json
from math import * 
from functools import partial

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(320,100)    
        self.setWindowTitle('aaaa')
        self.setStyleSheet("QMainWindow\
        {\
            background-color:white;\
            color:white;\
            margin:0px\
        }")
        self.InitializeWindow()
        self.i=0

    def InitializeWindow(self):
        self.statebar=QWidget(self)
        self.statebar.setGeometry(0, 40, 320, 54)
        print(sys._getframe().f_lineno)
        self.statebar.setStyleSheet("QWidget{background-color:#1EC5CD}")
        self.th_countdown=threading.Thread(target=self.countdown,args=())
        self.th_countdown.setDaemon(True)
        self.th_countdown.start()

        self.message_main=QLabel(self.statebar)
        self.message_main.setGeometry(150,7,40,37)
        self.message_main.setStyleSheet("background:transparent;color:white;margin:0px;font-size:45px;font-weight:bold")
        self.message_main.setWordWrap(True)
        self.message_main.hide()
        self.message_main.setAlignment(Qt.AlignTop|Qt.AlignLeft)
        self.message_signature=QLabel(self.statebar) …
Run Code Online (Sandbox Code Playgroud)

python python-multithreading qtstylesheets pyside2

4
推荐指数
1
解决办法
1128
查看次数

在并发请求的情况下,将数据存储在 Django 应用程序的“线程本地存储”中是否安全?

我在很多地方都看到,使用线程本地存储来存储 Django 应用程序中的任何数据并不是一个好的做法。但这是我存储请求对象的唯一方法。我需要存储它,因为我的应用程序具有复杂的结构。而且我无法继续在每个函数调用或类初始化时传递请求对象。

我需要将请求对象中的 cookie 和标头传递给我在应用程序中不同位置进行的一些 api 调用。

我将此用作参考: https://blndxp.wordpress.com/2016/03/04/django-get-current-user-anywhere-in-your-code-using-a-middleware/

所以我正在使用中间件,如参考文献中所述。而且,这就是请求的存储方式

from threading import local
_thread_locals = local()
_thread_locals.request = request
Run Code Online (Sandbox Code Playgroud)

并且,这就是获取数据的方式:

getattr(_thread_locals, "request", None)
Run Code Online (Sandbox Code Playgroud)

那么存储在线程中的数据是否是该特定请求的本地数据呢?或者,如果同时发生另一个请求,它们是否都使用相同的数据?(这当然不是我想要的)

或者有没有新的方法来处理这个老问题(全局存储请求对象)

注意:我也在async我的 Django 应用程序中的某些地方使用(如果这很重要的话)。

python django python-multithreading python-3.x django-rest-framework

4
推荐指数
1
解决办法
2104
查看次数

FastAPI 和 Python 线程

我对 FastAPI 和附加线程产生有一个小问题。假设我有一个为两个端点提供服务的应用程序。

  1. 其中之一是/create_user在某个数据库中创建用户
  2. 其他的只是/ping。进行 Ping 的原因很简单,因为我的应用程序在 Kubernetes 中运行,并且它通过发送 GET 请求并接收 response_code 200 来不断检查我的应用程序是否处于活动状态。
  3. 此外,我有一个单独的进程threading.Thread,它从外部服务接收一些密钥。Key有TTL,所以需要时常更新。

问题是,当我通过第一个端点加载数据时,我正在加载的数据库速度非常慢,最多可以响应 10 秒。在那一刻,所有其他端点(包括/ping)都被锁定。所以 k8s 认为我的应用程序已死并尝试回滚它。

我可以简单地尝试增加工作人员的数量,这些工作人员通过命令为应用程序提供服务uvicorn main:app --workers 4 ,但每个工作人员也会产生额外的线程,并且日志中的输出看起来像这样

INFO:     Application startup complete.
Hello from additional thread
INFO:     Started server process [88030]
Hello from additional thread 
INFO:     Waiting for application startup
Hello from additional thread Hello from additional thread
INFO:     Application startup complete. Hello from additional thread
Run Code Online (Sandbox Code Playgroud)

我的问题是有可能只产生一个额外的线程与多个gunicorn工人?

这是我的 main.py 中的代码片段

@app.post("/api/v1/create_user")
async def …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-multithreading python-3.7 fastapi

4
推荐指数
1
解决办法
2万
查看次数

如何捕获多个线程的异常?

我有一组想要在线程中执行的函数。其中一些函数可能会引发我想要捕获的特定异常,分别为每个线程。

我尝试了一些类似的事情

import threading

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    try:
        myfun.start()
    except MyException:
        print("caught MyException")
Run Code Online (Sandbox Code Playgroud)

我预计会看到caught MyException两次,每个线程一次。但只有一个。

是否可以独立地捕获线程中的异常?(换句话说:当线程引发异常时,在调用该线程的代码中对其进行管理?)

python multithreading exception python-multithreading python-3.x

4
推荐指数
1
解决办法
1361
查看次数

Python:'thread._local对象没有属性'todo'

我目前正在使用线程和所有这些来编写基于python的数据报服务器.

我遇到了以下问题:我使用多个分配线程将传入的包分配给不同的处理线程.在Processing Threads中,我使用threading.local()来跟踪线程局部变量.

我目前正在测试我的服务器在高负载期间的反应(2000个数据包在~2秒内),并且发现了local() - Object的奇怪行为.

似乎它在一段时间内工作得很好,然后,在某些时候,它会引发异常:

Exception in thread 192.168.1.102: # <-- This is the Processing Thread
Traceback (most recent call last):
  File "/opt/lib/python2.7/threading.py", line 552, in __bootstrap_inner
    self.run()
  File "/volume1/home/Max/Python/MyThread/pyProcThread.py", line 37, in run
    print self.loc.father
AttributeError: 'thread._local' object has no attribute 'father'

# The following three lines are debug
# This is the Allocation thread that has called the Processing thread
<Thread(192.168.1.102, started 1106023568)> 
# This confirms that the queue it tries to access exists
<Queue.Queue instance …
Run Code Online (Sandbox Code Playgroud)

python multithreading thread-local python-multithreading

3
推荐指数
1
解决办法
4263
查看次数

Python Grequests xml响应

问题的快速问题,因为它的文档相当稀疏.从发送的请求中返回xml响应的最佳方法是什么?我找不到获取状态代码以外的响应的方法.有人能指出我正确的方向吗?grequest甚至可以返回xml响应吗?我应该只使用请求并自己进行线程化吗?继承文档代码

import grequests

urls = [
'http://www.heroku.com',
'http://python-tablib.org',
'http://httpbin.org',
'http://python-requests.org',
'http://kennethreitz.com'
]
rs = (grequests.get(u) for u in urls)
grequests.map(rs)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是你如何从请求映射到实际获取xml响应?提前致谢.

python xml python-multithreading python-requests grequests

3
推荐指数
1
解决办法
2068
查看次数

不能使用setParseAction()方法来pickle Pyparsing表达式.需要多处理

我的原始问题是我正在尝试执行以下操作:

def submit_decoder_process(decoder, input_line):
    decoder.process_line(input_line)
    return decoder

self.pool = Pool(processes=num_of_processes)
self.pool.apply_async(submit_decoder_process, [decoder, input_line]).get()
Run Code Online (Sandbox Code Playgroud)

解码器在这里有点介绍,但重要的是解码器是一个用调用setParseAction()的PyParsing表达式初始化的对象.这会使多处理使用的pickle失败,这反过来又失败了上面的代码.

现在,这是我已经孤立和简化的pickle/PyParsing问题.由于pickle失败,以下代码会产生错误消息.

import pickle
from pyparsing import *

def my_pa_func():
    pass

pickle.dumps(Word(nums).setParseAction(my_pa_func))
Run Code Online (Sandbox Code Playgroud)

错误信息:

pickle.PicklingError: Can't pickle <function wrapper at 0x00000000026534A8>: it's not found as pyparsing.wrapper
Run Code Online (Sandbox Code Playgroud)

现在,如果你删除调用.setParseAction(my_pa_func),它将没有问题:

pickle.dumps(Word(nums))
Run Code Online (Sandbox Code Playgroud)

我怎么能绕过它呢?多处理使用泡菜,所以我猜不出它.据说使用dill的pathos包不够成熟,至少,我在Windows-64bit上安装它时遇到问题.我真的在这里摸不着头脑.

python pickle pyparsing python-multithreading python-multiprocessing

3
推荐指数
1
解决办法
751
查看次数

Sublime Text 2 API中的哪些操作是线程安全的?

在Sublime Text 3 API中,所有操作都是线程安全的:

穿线

所有API函数都是线程安全的......

但在Sublime Text 2 API中,情况并非如此.由于我亲自学会了我的不满,一些操作将以不可预测且依赖于操作系统的方式在从主线程以外的线程调用消息时失败

RuntimeError:必须在主线程上调用,考虑使用sublime.set_timeout(函数,超时)

我可以在Sublime Text 2文档(强调我的)中找到关于线程安全的一个保证:

set_timeout(回调,延迟)

在给定的延迟(以毫秒为单位)后调用给定的回调.具有相等延迟的回调将按照添加的顺序运行.从多个线程调用setTimeout是安全的.

但是将所有内容包装在set_timeout电话中是单调乏味且难以理解的.如果我的目标是支持Sublime Text 2,还是大量使用set_timeout唯一的方法,是否有任何其他API方法我可以安全地从主线程中使用?

multithreading python-multithreading sublimetext sublimetext2 sublime-text-plugin

3
推荐指数
1
解决办法
307
查看次数

限制XGBoost使用的线程数

我想将XGBoost用于在线生产(Python 2.7 XGBoost API)。为了能够做到这一点,我想在预测操作中控制和限制XGBoost使用的线程数。

我正在使用XGBoost(xgboost.XGBRegressor)提供的sklearn兼容回归器,并一直尝试在回归器的构造函数中使用param nthread来将最大线程数限制为1。

不幸的是,无论nthread中设置的值如何,XGBoost都会继续使用多个线程。

还有另一种方法来限制XGBoost并强制它使用n = 1个线程执行预测操作吗?

python python-multithreading scikit-learn xgboost

3
推荐指数
2
解决办法
764
查看次数