标签: python-multithreading

Django会话线程安全吗?

我将字典存储在Django会话中,可以通过多个线程访问.所有线程都可以更新该字典,线程也从字典中获取值以运行该进程.我想知道Django Session是线程安全的还是我必须使用锁或信号量?

典型例子:

Thread1:
threadDict = request.session.get('threadDict', None)
if threadDict['stop']:
   #break the for loop exit the thread
else:
   #do some processing and update some values in thread dictionary
   threadDict['abc'] = 0
   request.session['threadDict'] = threadDict (Point1)

def someFunction():
    #this function is used to send stop signal to thread
    threadDict = request.session.get('threadDict', None)
    threadDict['stop'] = True
    request.session['threadDict'] = threadDict (Point2)
Run Code Online (Sandbox Code Playgroud)

是否有可能Point2在会话更新后更新线程字典Point1也更新它,然后我stop退出线程丢失.

更多信息

ajax请求启动四个线程,从4个不同的URL下载样本.为什么我使用线程?因为我想向用户显示当前正在下载的样本和剩下的样本.所有线程都将在会话中的字典中更新其状态.线程启动后,我每隔两秒钟发出一次ajax请求,并从会话中获取字典并读取线程的当前状态.但是这个想法失败了,因为线程独立于请求及其会话.每个ajax请求肯定都有它的会话,但是我无法将该会话传递给线程,因为当它们一旦开始时它们独立于世界的其余部分(可能是我可以通过它但我可能不会快速通过它,因为处理正在由线程).所以要解决这个问题,我选择缓存框架而不是会话.因为缓存可以从任何地方访问.线程将它们的状态存储在字典中并重新放入缓存中,每两秒钟后我从缓存中获取字典并读取状态.根据我的经验,缓存还有一件事是线程安全的.因此,对于四个线程,我使用了四个字典.

python django thread-safety python-multithreading

9
推荐指数
1
解决办法
3566
查看次数

如何加快与子进程的通信

我使用Python 2 subprocessthreading螺纹采取标准输入,处理它与二进制文件A,B以及C和写入修改的数据标准输出.

这个脚本(让我们称之为:) A_to_C.py非常慢,我想学习如何解决它.

一般流程如下:

A_process = subprocess.Popen(['A', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
produce_A_thread = threading.Thread(target=produceA, args=(sys.stdin, A_process.stdin))

B_process = subprocess.Popen(['B', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
convert_A_to_B_thread = threading.Thread(target=produceB, args=(A_process.stdout, B_process.stdin))

C_process = subprocess.Popen(['C', '-'], stdin=subprocess.PIPE)
convert_B_to_C_thread = threading.Thread(target=produceC, args=(B_process.stdout, C_process.stdin)) 

produce_A_thread.start()
convert_A_to_B_thread.start()
convert_B_to_C_thread.start()

produce_A_thread.join()
convert_A_to_B_thread.join()
convert_B_to_C_thread.join()

A_process.wait()
B_process.wait()
C_process.wait()
Run Code Online (Sandbox Code Playgroud)

这个想法是标准输入进入A_to_C.py:

  1. A二进制处理标准输入的块,并创建A与该功能-output produceA.
  2. B二进制过程的块A的标准输出并产生B通过功能-output produceB.
  3. C二进制过程的块B …

python multithreading subprocess python-multithreading

9
推荐指数
3
解决办法
2801
查看次数

在Python中重新启动一个线程

我正在尝试为Python 3.4中的项目制作线程飞行软件,其中我需要线程重新启动,以防在传感器读取期间发生I/O错误或其他类似的侥幸崩溃.因此,我正在制作一个看门狗来检查线程是否已经死亡并重新启动它们.

起初我试图检查线程是否不再存在并重新启动它,这样做:

>>> if not a_thread.isAlive():
...     a_thread.start()
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "c:\Python34\lib\threading.py", line 847, in start
    raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Run Code Online (Sandbox Code Playgroud)

threadingPython本身的角度来看,这种行为是有道理的,但这使我的工作更加困难.所以我使用字典实现了一个解决方案来存储初始线程并将其复制到一个新对象并在必要时启动它.不幸的是,这也不起作用.这是一个基本的例子:

import threading
import logging
import queue
import time
from copy import copy, deepcopy

def a():
    print("I'm thread a")
def b():
    print("I'm thread b")

# Create thread objects
thread_dict = {
'a': threading.Thread(target=a, name='a'),
'b': threading.Thread(target=b, name='b')
} …
Run Code Online (Sandbox Code Playgroud)

python multithreading copy python-multithreading

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

python:tkinter显示来自网络摄像头的视频并进行QR扫描

我一直在尝试创建一个tkinter顶级窗口,用于流式传输视频格式网络摄像头并进行QR扫描.我从SO获得了这个QR扫描代码,而另一个代码只是从网络摄像头更新图像而不是在tkinter标签上流式传输视频.

我试图将这两者结合起来,以便使用标签更新来自网络摄像头的图像的顶层窗口和关闭顶层窗口的关闭按钮.当它流式传输图像时,它可以扫描QR码,如果扫描成功,网络摄像头和顶层窗口将关闭.

这是我试过的.

import cv2
import cv2.cv as cv
import numpy
import zbar
import time
import threading
import Tkinter
from PIL import Image, ImageTk

class BarCodeScanner(threading.Thread, Tkinter.Toplevel):
    def __init__(self):
        # i made this as a global variable so i can access this image
        # outside ie,. beyond the thread to update the image on to the  tkinter window
        global imgtk
        imgtk = None
        threading.Thread.__init__(self)
        self.WINDOW_NAME = 'Camera'
        self.CV_SYSTEM_CACHE_CNT = 5 # Cv has 5-frame cache
        self.LOOP_INTERVAL_TIME …
Run Code Online (Sandbox Code Playgroud)

python webcam opencv tkinter python-multithreading

9
推荐指数
1
解决办法
3274
查看次数

Python namedtuple作为apply_async(..)回调的参数

我正在写一个简短的程序,我想异步调用一个函数,这样它就不会阻塞调用者.为此,我正在使用Poolpython的multiprocessing模块.

在异步调用的函数中,我想返回一个namedtuple以适应我程序其余部分的逻辑,但我发现a namedtuple似乎不是从生成的进程传递给回调的受支持类型(可能是因为它不能被腌制).这是问题的最低限度.

from multiprocessing import Pool
from collections import namedtuple

logEntry = namedtuple("LogEntry", ['logLev', 'msg'])

def doSomething(x):
    # Do actual work here
    logCode = 1
    statusStr = "Message Here"
    return logEntry(logLev=logCode, msg=statusStr)

def callbackFunc(result):
    print(result.logLev)
    print(result.msg)

def userAsyncCall():
    pool = Pool()
    pool.apply_async(doSomething, [1,2], callback=callbackFunc)

if __name__ == "__main__":
    userAsyncCall() # Nothing is printed

    # If this is uncommented, the logLev and status are printed as expected:
    # y = logEntry(logLev=2, msg="Hello World") …
Run Code Online (Sandbox Code Playgroud)

python python-multithreading python-2.7 python-3.x

9
推荐指数
1
解决办法
1170
查看次数

TensorFlow:从多个线程中排队和出列队列

我试图解决的问题如下:我有一个trainimgs文件名列表.我已经定义了一个

  • tf.RandomShuffleQueue与它capacity=len(trainimgs)min_after_dequeue=0.
  • tf.RandomShuffleQueue预计这将填充trainimgs指定epochlimit的次数.
  • 预计许多线程将并行工作.每个线程从一个元素中取出一个元素tf.RandomShuffleQueue并对其进行一些操作并将其排入另一个队列.我有那个部分是正确的.
  • 然而,一旦1 epochtrainimgs已被处理和tf.RandomShuffleQueue为空,前提是当前时期e < epochlimit,队列必须再次被填满和线程必须重新工作.

好消息是:我已经让它在某种情况下工作(最后见PS !!)

坏消息是:我认为有更好的方法可以做到这一点.

我现在使用的方法如下(我已经简化了功能并删除了基于预处理和后续排队的e图像处理,但处理的核心保持不变!!):

with tf.Session() as sess:
    train_filename_queue = tf.RandomShuffleQueue(capacity=len(trainimgs), min_after_dequeue=0, dtypes=tf.string, seed=0)
    queue_size = train_filename_queue.size()
    trainimgtensor = tf.constant(trainimgs)
    close_queue = train_filename_queue.close()
    epoch = tf.Variable(initial_value=1, trainable=False, dtype=tf.int32)
    incrementepoch = tf.assign(epoch, epoch + 1, use_locking=True)
    supplyimages = train_filename_queue.enqueue_many(trainimgtensor)
    value = train_filename_queue.dequeue()

    init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init_op)
    coord = tf.train.Coordinator() …
Run Code Online (Sandbox Code Playgroud)

python-multithreading tensorflow

9
推荐指数
1
解决办法
1013
查看次数

在新的控制台窗口中打开Python线程

我正在尝试创建一个程序,它将启动视图窗口(控制台)和命令行.在视图窗口中,它将显示常量更新,而命令行窗口将用于raw_input()接受影响视图窗口的命令.我正在考虑使用线程,但我不知道如何在新的控制台窗口中启动线程.我该怎么办?

python linux windows multithreading python-multithreading

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

每隔x分钟执行一次函数:sched或threading.Timer?

我需要每隔x分钟编写一次给定方法的执行.

我找到了两种方法:第一种是使用sched模块,第二种是使用模块Threading.Timer.

第一种方法:

import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
    sc.enter(60, 1, do_something, (sc,))

s.enter(60, 1, do_something, (s,))
s.run()
Run Code Online (Sandbox Code Playgroud)

第二个:

import threading

def do_something(sc): 
    print "Doing stuff..."
    # do your stuff
   t = threading.Timer(0.5,do_something).start()

do_something(sc)
Run Code Online (Sandbox Code Playgroud)

有什么区别,如果有一个比另一个好,哪一个?

python timer python-multithreading

8
推荐指数
1
解决办法
5640
查看次数

在python中演奏和弦

我想做一个平台来演奏和吉他一样的和弦.例如 - 要播放E和弦,它会播放[0,2,2,1,0,0](从Low-E字符串到High-E字符串).

我试图通过同时播放所有不同的字符串(通过使用线程)在python上弹奏和弦.

问题是,每次我开始播放下一个字符串时,似乎最后一个字符串停止播放,而新的字符串会替换它.所以我在弹奏和弦后听到的是最高弦(最后一个).

我没有正确使用线程吗?或者它是当前功能的问题?或者也许是winsound.Beep()函数可以处理这些事情?

这是我的代码:

from winsound import Beep
import threading
import time


def play(freq, dur):
    Beep(round(freq), round(dur))


def get_freq(string, fret):
    a3_freq = 220
    half_tone = 2 ** (1 / 12)

    higher_from_a3_by = 5 * (string - 2) + fret
    if string > 4:
        higher_from_a3_by += 1
    return a3_freq * half_tone ** higher_from_a3_by


def strum(string, fret, time):
    freq = get_freq(string, fret)
    t = threading.Thread(target=play, args=(freq, time))
    t.start()
    return t


def chord(frets, dur):
    threads = []
    for i in …
Run Code Online (Sandbox Code Playgroud)

python audio python-multithreading music-notation

8
推荐指数
1
解决办法
1206
查看次数

等效于 Python 3 中的 thread.interrupt_main()

在 Python 2 中有一个函数thread.interrupt_main()KeyboardInterrupt当从子线程调用时,它会在主线程中引发异常。

这也可以_thread.interrupt_main()在 Python 3 中使用,但它是一个低级的“支持模块”,主要用于其他标准模块。

在 Python 3 中这样做的现代方法是什么,大概是通过threading模块,如果有的话?

python multithreading keyboardinterrupt python-multithreading python-3.x

8
推荐指数
2
解决办法
4362
查看次数