标签: python-multithreading

线程的Django全局数据

我的单进程多线程 django 服务器中有一个共享的全局数据对象 - 一个经常使用但很少计算的对象。计算很耗时,所以我想分享结果。

我认为使用 django 的 LocalMemCache 来处理这个简单的数据是可行的。奇怪的是,它似乎适用于单个页面加载的多个 ajax 调用,但出于某种原因,当我在浏览器中重新加载页面时,缓存再次为空。

我究竟做错了什么?

有没有更好的办法?如果我使用线程锁控制写访问,全局变量是否也同样有效?

这基本上是我在做什么:

from threading import Lock
from django.core.cache import get_cache

my_lock = Lock()
cache = get_cache('default')

def get_global_data():
    my_lock.acquire()
    try:
        cached_data = cache.get('data')
        if not cached_data:
            cached_data = big_function_to_calculate_data()
            cache.set('data', cached_data)
    finally:
        my_lock.release()
    return cached_data

# settings.py defines my django LocMemCache as:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'my_server'
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

问题的根本原因是根据访问控制列表(这里不是代码的一部分)检索数据,该列表因请求类型(GET、POST)等而异。计算时,这是一个 POST 请求,其中包含一组访问,并且在读取它时是一个具有不同访问权限的 GET 请求,并且返回了一组不同(且无效)的结果。

python django multithreading django-cache python-multithreading

5
推荐指数
1
解决办法
1921
查看次数

如果 __init__ 只调用 super.__init__ 是否有必要?

我正在对类进行子threading.Thread类化,它目前看起来像这样:

class MyThread(threading.Thread):
    def __init__(self:
        super(MyThread, self).__init__()

    def run(self):
        # Do some stuff
Run Code Online (Sandbox Code Playgroud)

__init__在这种情况下是必需的吗?如果我省略它,它会自动调用吗?

python oop inheritance python-multithreading python-2.7

5
推荐指数
1
解决办法
327
查看次数

使用 Pyramid 和 rq 写入相同的日志文件

我正在使用 Pyramid 和rq,我想将 rq 工作作业记录在与我的 Pyramid 应用程序相同的文件中。

我的设置如下所示:

开发文件

# regular pyramid setup here...

[loggers]
keys = root, main

[handlers]
keys = console, debuglog

[formatters]
keys = generic

[logger_root]
level = DEBUG
handlers = console, debuglog

[logger_main]
level = DEBUG
handlers =
qualname = main

[handler_debuglog]
class = handlers.RotatingFileHandler
args = ('%(here)s/__logs/pyramid_debug.log','a')
level = DEBUG
formatter = generic

[formatter_generic]
format = %(asctime)s %(levelname)-8s [%(name)s][%(threadName)s] %(message)s
Run Code Online (Sandbox Code Playgroud)

主文件

from bunch import Bunch
from redis import Redis
from rq import Queue, …
Run Code Online (Sandbox Code Playgroud)

python logging multithreading python-multithreading pyramid

5
推荐指数
1
解决办法
1511
查看次数

如何通过线程在python中使用Event对象?

我有一个主要的 python 脚本,它启动一个在后台运行的线程。

poll = threading.Thread(target=poll_files, args=myargs)

我希望我的主脚本等到我的poll线程中发生特定的事情。我想使用一个 Event 对象。所以在我的主脚本中,我这样做:

trigger = threading.Event()

当我想等待时:

trigger.wait()

我的问题是,在我的poll线程中,如何将事件设置为 True?我知道我这样做:

trigger.set()

但我还需要trigger = threading.Event()在我的poll线程里面吗?

python events python-multithreading

5
推荐指数
1
解决办法
5985
查看次数

ThreadPoolExecutor 日志记录?(Python)

我有一些代码看起来像

with futures.ThreadPoolExecutor(max_workers=2) as executor:
    for function in functions:
        executor.submit(function)
Run Code Online (Sandbox Code Playgroud)

我将如何记录执行程序当前正在处理哪个函数?我可能有也可能没有能力从函数内登录 - 希望执行器本身记录类似的东西

print "handling process {i}".format(i=current_process)
Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题的任何想法?

python multithreading threadpool python-multithreading

5
推荐指数
1
解决办法
2872
查看次数

Python asyncio 等待线程

我有一种情况,我有一个“服务器”线程,它应该侦听来自其他服务器线程的调用/事件,同时执行其他一些代码。最近我在 Node.js 上做了很多工作,所以我认为使用 async/await 创建一个事件循环会很好,我可以在其中等待其他线程加入事件循环并在它们最终加入时处理它们的响应。

为了测试这个想法,我在 Python 3.5 中编写了以下测试脚本:

# http://stackabuse.com/python-async-await-tutorial/
# Testing out Python's asynchronous features
import asyncio
from time import sleep
import threading
from threading import Thread
import random

class MyThread(Thread):

    def __init__(self, message):
        Thread.__init__(self)
        self._message = message

    def run(self):
        self._return = self._message + " oli viesti"
        a = random.randint(1, 5)
        print("Sleep for ", a)
        sleep(a)
        print("Thread exiting...")


    def join(self):
        Thread.join(self)
        return self._return



async def send(message):
    t = MyThread(message)  # daemon = True
    t.start()
    print("asd")
    return t.join()

async …
Run Code Online (Sandbox Code Playgroud)

python asynchronous python-multithreading async-await

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

Python Webdriver 多线程

我正在尝试使用以下代码生成多个 webdriver 实例:http : //www.ibm.com/developerworks/aix/library/au-threadingpython/

import time
import Queue
import urllib2
import threading
from selenium import webdriver
from BeautifulSoup import BeautifulSoup
hosts = ["http://yahoo.com", "http://google.com", "http://amazon.com",
    "http://ibm.com", "http://apple.com"]
queue = Queue.Queue
out_queue = Queue.Queue

class Login_Driver(threading.Thread):
    def __init__(self, queue, out_queue, driver):
        threading.Thread.__init__(self)
        self.queue = queue
        self.out_queue = out_queue
        self.driver = driver
        print driver.title
    def run(self):
        while True:
            #grabs host from queue
            host = self.queue.get()
            #grabs urls of hosts and then grabs chunk of webpage
            driver.get(host)
            chunk = driver.page_source()
            #place …
Run Code Online (Sandbox Code Playgroud)

python python-multithreading selenium-webdriver

5
推荐指数
1
解决办法
4424
查看次数

Python 子进程 Popen.terminate() 仍然停留在 wait()

我正在尝试使用 RPi 实现无线电播放器。目标是设置播放列表并在播放列表填充后开始播放。一旦停止代码被执行,播放器和收音机进程就会退出。

无线电进程很好地终止,但播放器进程即使在调用终止后仍然保持等待。如果再次调用停止代码,则播放器进程终止

尝试的事情:

  1. 重新排序等待命令(播放器,收音机)/(收音机,播放器)
  2. 类似地重新排序终止命令
  3. 使用 kill 而不是终止挂起 RPi

玩家代码:

while playlist:
    player = subprocess.Popen(
            ["avconv", "-i", "Music/%s" % playlist[0], "-f", "s16le", "-ar", 
            "22.05k", "-ac", "1", "-"], stdout=subprocess.PIPE)

    radio = subprocess.Popen(["./pifm", "-", freq], stdin=player.stdout)

    radio.wait()
    print "************ exiting from radio :)"
    player.wait()
    print "************ exiting from player :)"

    playlist.pop(0)
player = None
radio = None
Run Code Online (Sandbox Code Playgroud)

播放器停止代码(从另一个线程调用):

print "************ stop requested"

if radio and radio.poll() is None:
    print "************ terminating radio :)"
    radio.terminate()

if player and player.poll() is None: …
Run Code Online (Sandbox Code Playgroud)

python subprocess python-multithreading raspberry-pi

5
推荐指数
1
解决办法
1320
查看次数

多线程 HTTP GET 请求在大约 900 次下载后严重减慢

我正在尝试使用从 Amazon S3 下载大约 3,000 个文件(每个文件的大小可能为 3 MB)requests_futures,但下载速度在大约 900 个后严重减慢,并且实际上开始运行速度比基本的 for 循环慢。

我似乎没有耗尽内存或 CPU 带宽。然而,看起来我机器上的 Wifi 连接速度几乎没有变慢:我从几千个数据包/秒下降到只有 3-4 个。最奇怪的是,在 Python 进程退出并重新启动 wifi 适配器之前,我无法加载任何网站。

到底是什么原因导致了这种情况,我该如何调试它?

如果有帮助,这是我的 Python 代码:

import requests
from requests_futures.sessions import FuturesSession
from concurrent.futures import ThreadPoolExecutor, as_completed

# get a nice progress bar
from tqdm import tqdm

def download_threaded(urls, thread_pool, session):
    futures_session = FuturesSession(executor=thread_pool, session=session)
    futures_mapping = {}
    for i, url in enumerate(urls):
        future = futures_session.get(url)
        futures_mapping[future] = i
    
    results = [None] * len(futures_mapping)

    with …
Run Code Online (Sandbox Code Playgroud)

multithreading python-multithreading python-3.x python-requests concurrent.futures

5
推荐指数
1
解决办法
624
查看次数

如何在一段时间后停止运行我的线程?

我需要在一段时间后停止运行我的线程,在这个例子中我只放了120秒.我尝试使用这种方法,它不起作用.

from threading import Thread
from Queue import Queue
import os
import time

timeout = 120   # [seconds]

timeout_start = time.time()

#while True :


def OpenWSN ():
    os.system("./toto")

def Wireshark():
    os.system(" tshark -i tun0 -T ek -w /home/ptl/PCAP_Brouillon/Sim_Run3rd.pcap > /dev/null ")


def wrapper1(func, queue):
    queue.put(func())

def wrapper2(func, queue):
    queue.put(func())


q = Queue()
Thread(target=wrapper1, args=(OpenWSN, q)).start()
Thread(target=wrapper2, args=(Wireshark,  q)).start()

#print (time.time())
print ("***************** End Simulation *************************")
os.system("quit")
Run Code Online (Sandbox Code Playgroud)

python shell python-multithreading

5
推荐指数
1
解决办法
142
查看次数