标签: python-multithreading

如何让精灵在Pygame和Python中的所有计算机上均匀移动

我在均匀移动精灵方面遇到了问题; 目前我正在使用while循环移动它们,问题是计算机越快,循环越快,精灵移动得越快.我已经尝试了pygame中的定时器/时钟功能(等待?),并且它在等待时冻结光标,因此将光标按到跳跃状态.

多线程的答案是什么?

这是我的问题视频; http://www.youtube.com/watch?v=cFawkUJhf30

python multithreading pygame sprite python-multithreading

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

dummy_threading 有什么作用?

我dummy_threading什么时候用?

我曾认为它可能会用模拟线程替换系统级线程,以防系统级线程不适用于 Python。

但是当我运行这个时:

import dummy_threading as threading

semaphore = threading.Semaphore()
def f(i):
    semaphore.acquire()
    print i
for i in xrange(10):
    threading.Thread(target=f, args=(i,)).start()
for _ in xrange(10):
    semaphore.release()
Run Code Online (Sandbox Code Playgroud)

我得到0,并且程序不会终止。不仅如此,Python 还会莫名其妙地继续消耗我计算机的内存,直到它一无所有。

当我运行这个:

import threading

semaphore = threading.Semaphore()
def f(i):
    semaphore.acquire()
    print i
for i in xrange(10):
    threading.Thread(target=f, args=(i,)).start()
for _ in xrange(10):
    semaphore.release()
Run Code Online (Sandbox Code Playgroud)

我得到0 1 3 5 7 9 2 4 6 8了预期的结果。

我一定是误会了dummy_threading。我什么时候使用它?

仅供参考,我在 Windows 7 和 Fedora 18 上进行了比较,并得到了相同的结果。

编辑:然而,以下给出0 1 …

python multithreading python-multithreading python-2.7

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

在python中使用线程/多处理同时进行多个计算

我有一个数字列表。我想对列表中的每个数字执行一些耗时的操作,并制作一个包含所有结果的新列表。这是我所拥有的简化版本:

def calcNum(n):#some arbitrary, time-consuming calculation on a number
  m = n
  for i in range(5000000):
    m += i%25
    if m > n*n:
      m /= 2
  return m

nums = [12,25,76,38,8,2,5]
finList = []

for i in nums:
  return_val = calcNum(i)
  finList.append(return_val)

print(finList)
Run Code Online (Sandbox Code Playgroud)

现在,我想利用我的 CPU 中的多个内核,并为每个内核分配处理其中一个数字的任务,并且由于“数字计算”功能从头到尾都是独立的,我认为这将是相当简单,是多处理/线程的完美情况。

我的问题是,我应该使用哪个(多处理或线程?),最简单的方法是什么?

我用在其他问题中找到的各种代码进行了测试,以实现这一点,虽然它运行良好,但似乎没有进行任何实际的多线程/处理,并且与我的第一次测试一样长:

from multiprocessing.pool import ThreadPool

def calcNum(n):#some arbitrary, time-consuming calculation on a number
  m = n
  for i in range(5000000):
    m += i%25
    if m > n*n:
      m /= 2
  return m

pool …
Run Code Online (Sandbox Code Playgroud)

python multithreading multiprocessing python-multithreading

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

理解thread.join(超时)

因此,在超时 PARAM,一个线程,应停止后的线程超时秒(如果还没有终止).

在我的软件中,我正在尝试替换Queue.Queue.join()(它包含每个线程的项目:每个线程将运行Queue.Queue.task_done())如果线程没有终止可能会停止软件.因此,如果一个线程(除其他50之外)没有终止,那么它就会被冻结.

我希望每个线程在5秒内停止,例如.所以我将以超时5秒开始每个线程.这是对的吗?

码

import threading
import time

def tt(name, num):
    while True:
        num += 0.5
        print 'thread ' + str(name) + ' at time ' + str(num)
        time.sleep(0.5)


for i in range(3):
    t=threading.Thread(target=tt, args=(i, 0))
    t.setDaemon(True)
    t.start()
    t.join(timeout=1)

print 'end'
Run Code Online (Sandbox Code Playgroud)

结果

它没有正常工作..每个线程应在1秒后停止.线程0在3秒后停止,线程1在2秒后停止.

thread 0 at time 0.5
thread 0 at time 1.0
thread 1 at time 0.5
thread 0 at time 1.5
thread 0 at time 2.0
thread 1 at …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-multithreading

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

关于使用Queue()/ deque()和类变量进行通信和"毒丸"的过程与线程

我想创建一个Thread或一个在While True循环中永远运行的进程.

我需要以队列的形式向工作人员发送和接收数据,可以是multiprocessing.Queue()或collections.deque().我更喜欢使用collections.deque(),因为它明显更快.

我还需要能够最终杀死这个工作者(因为它运行了一段时间的True循环.这里有一些测试代码,我把它们放在一起试图理解线程,进程,队列和deque之间的区别.

import time
from multiprocessing import Process, Queue
from threading import Thread
from collections import deque

class ThreadingTest(Thread):

    def __init__(self, q):
        super(ThreadingTest, self).__init__()
        self.q = q
        self.toRun = False

    def run(self):
        print("Started Thread")
        self.toRun = True
        while self.toRun:
            if type(self.q) == type(deque()):
                if self.q:
                    i = self.q.popleft()
                    print("Thread deque: " + str(i))
            elif type(self.q) == type(Queue()):
                if not self.q.empty():
                    i = self.q.get_nowait()
                    print("Thread Queue: " + str(i))

    def stop(self):
        print("Trying to stop Thread")
        self.toRun = False
        while …
Run Code Online (Sandbox Code Playgroud)

python multiprocessing python-multithreading python-3.x python-multiprocessing

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

如何在 python 中捕获 Joblib/并行异常?

我有一个joblib's的用例Parallel, delayed。我已经包含了一些在某些条件下终止工人的功能。然而,当我这样做,我随机产生JoblibWebdriverException,Multiprocessing exception,JoblibURLerror,或只error。

令我高兴的是,我在docs 中没有找到关于如何(定义?)/捕获异常的任何部分。

当我做:

    try:
       Parallel(delayed(function))
    except (JoblibWebdriverException | error | 'Multiprocessing exception'): 
    # written with separate excepts in original code
       log_errors()
Run Code Online (Sandbox Code Playgroud)

我屈服,name JoblibWebdriverException not defined然后是:

---------
Sub-process traceback
---------
Multiprocessing exception:
(trace stack)
Run Code Online (Sandbox Code Playgroud)

在python中使用Parallel时如何捕获未定义的joblib异常?

exception-handling try-catch python-multithreading joblib python-multiprocessing

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

Python 线程 run() 阻塞

当我创建以下内容时,我试图创建一个可以被异常终止的线程类(因为我试图让线程等待一个事件):

import sys

class testThread(threading.Thread):
    def __init__(self):
        super(testThread,self).__init__()
        self.daemon = True

    def run(self):
        try:
            print('Running')
            while 1:
                pass
        except:
            print('Being forced to exit')

test1 = testThread()
test2 = testThread()

print(test1.daemon)
test1.run()
test2.run()

sys.exit()
Run Code Online (Sandbox Code Playgroud)

但是,运行该程序只会打印出一个 Running 消息,直到另一个终止。这是为什么?

python multithreading python-multithreading python-3.x

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

RecursionError:使用线程时超出了最大递归深度

所以我收到错误

[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
Run Code Online (Sandbox Code Playgroud)

我正在运行的代码是

import threading

def hello_world(a):
    threading.Timer(2.0, hello_world(a)).start() # called every minute
    print(a)
    print("Hello, World!")

hello_world('a')
Run Code Online (Sandbox Code Playgroud)

我注意到当hello_world函数中没有参数时不会发生错误。但是一旦我需要将参数传递给函数,我就会收到错误消息。有人可以解释为什么会这样以及如何解决吗?

python python-multithreading

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

何时在 Python 中使用线程本地内存?

我刚开始使用 Python 并偶然发现了线程本地内存。我写了一个使用线程的小程序:

#!/usr/bin/env python3

import logging
import signal
import threading
import time

class WorkerThread(threading.Thread):
    def __init__(self, idx):
        threading.Thread.__init__(self)
        self.thread_index = idx
        self.thread_alive = True

    def run(self):
        logging.info(f'Thread {self.thread_index} is starting up!')

        while self.thread_alive:
            logging.info(f'Thread {self.thread_index} is still running.')
            time.sleep(1)

        logging.info(f'Thread {self.thread_index} is stopping!')

    def kill(self):
        self.thread_alive = False

def main():
    logging.basicConfig(format = '%(levelname)s: %(message)s', level = logging.INFO)

    def signal_handler(sig, frame):
        logging.info('Ctrl+c pressed, killing threads and shutting down ...')
        nonlocal threads
        for thread in threads:
            thread.kill()

    signal.signal(signal.SIGINT, signal_handler)

    logging.info('Signal handler …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-multithreading

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

在 Python 中并行运行多个任务的最佳方式是什么

我有一个功能:

import time

def all_40k():
    for _ in range(400000):
        print('validate')
        print('parsing')
        print('inserting')
if __name__ == '__main__':
    start_time = time.time()
    all_40k()
    print(f'used time:{time.time()-start_time}')
Run Code Online (Sandbox Code Playgroud)

输出是:

used time:9.545064210891724
Run Code Online (Sandbox Code Playgroud)

因为这个相同的函数重复了 40k 次,所以我希望有 4 个并行函数同时运行,每个函数运行 10k,理想情况下这会快 4 倍。

所以我首先尝试了多线程:

import threading
import time
def first_10k():
    for _ in range(100000):
        print('validate')
        print('parsing')
        print('inserting')


def second_10k():
    for _ in range(100000):
        print('validate')
        print('parsing')
        print('inserting')

def third_10k():
    for _ in range(100000):
        print('validate')
        print('parsing')
        print('inserting')

def forth_10k():
    for _ in range(100000):
        print('validate')
        print('parsing')
        print('inserting')

thread1 = threading.Thread(target=first_10k)
thread2 = threading.Thread(target=second_10k) …
Run Code Online (Sandbox Code Playgroud)

python multithreading python-multithreading python-asyncio python-multiprocessing

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