这是最奇怪的事情!
我有一个用Python编写的多线程客户端应用程序.我正在使用线程来同时下载和处理页面.我会使用cURL多句柄,除了瓶颈肯定是此应用程序中的处理器(而不是带宽),因此使用线程池更有效.
我有一个64b i7摇摆16GB内存.仡.我在听Pandora和拖钓Stackoverflow和BAM时启动80个线程!父进程有时以消息结束
Killed
其他时候,单个页面(这是Chrome中自己的进程)将会死亡.其他时候整个浏览器崩溃了.
如果你想在这里看到一些代码是它的要点:
这是父进程:
def start( ):
while True:
for url in to_download:
queue.put( ( url, uri_id ) )
to_download = [ ]
if queue.qsize( ) < BATCH_SIZE:
to_download = get_more_urls( BATCH_SIZE )
if threading.activeCount( ) < NUM_THREADS:
for thread in threads:
if not thread.isAlive( ):
print "Respawning..."
thread.join( )
threads.remove( thread )
t = ClientThread( queue )
t.start( )
threads.append( t )
time.sleep( 0.5 )
Run Code Online (Sandbox Code Playgroud)
这是ClientThread的要点:
class ClientThread( threading.Thread ):
def __init__( self, queue ): …Run Code Online (Sandbox Code Playgroud) 在Windows上使用python 2.7.4(注意:WinXP - 下面的评论者建议在Win7上正常工作),我有一个脚本创建几个线程,每个线程通过Popen运行子进程,stdout/stderr重定向到文件和调用等待().每个Popen都有自己的stdout/stderr文件.每个进程返回后,我有时必须删除文件(实际上将它们移动到其他地方).
我发现在所有wait()调用返回之前我都无法删除stdout/stderr日志.在此之前,我得到"WindowsError:[错误32]该进程无法访问该文件,因为它正被另一个进程使用".看起来,只要至少有一个子进程打开,Popen就会以某种方式保留stderr文件,即使这些文件没有共享.
测试代码重现如下.
C:\ test1.py
import subprocess
import threading
import os
def retryDelete(p, idx):
while True:
try:
os.unlink(p)
except Exception, e:
if "The process cannot access the file because it is being used by another process" not in e:
raise e
else:
print "Deleted logs", idx
return
class Test(threading.Thread):
def __init__(self, idx):
threading.Thread.__init__(self)
self.idx = idx
def run(self):
print "Creating %d" % self.idx
stdof = open("stdout%d.log" % self.idx, "w")
stdef = open("stderr%d.log" % self.idx, "w")
p = …Run Code Online (Sandbox Code Playgroud) python windows-xp subprocess python-multithreading python-2.7
我有一个连接到许多服务器之一的Web服务器.Web服务器最多可以排队40个作业,每个作业可能需要20分钟或30个小时才能运行.
Web服务器使用套接字连接到serverlet,serverlet运行通过使用线程发送的作业.
我想对可以一次运行的线程(作业)的数量设置上限,比如3,一旦达到该限制,它就会保持主线程.当其中一个线程结束时,它允许主线程继续并拾取另一个作业.
# Wait for thread count to reduce before continuing
while threading.active_count() >= self.max_threads:
pass
Run Code Online (Sandbox Code Playgroud)
我目前正在使用循环使我的主线程等待,直到有一个免费线程可用.它有效,但感觉就像一个快速而肮脏的解决方案.我想知道是否有更好的方法可以做到这一点?
server.py
import socket
import sys
import urllib, urllib2
import threading
import cPickle
from supply import supply
class supply_thread(threading.Thread):
def __init__(self, _sock):
threading.Thread.__init__(self)
self.__socket = _sock
def run(self):
data = self.readline()
self.__socket.close()
new_supply = supply.supply(data)
new_supply.run()
def readline(self):
""" read data sent from webserver and decode it """
data = self.__socket.recv( 1024 )
if data:
data = cPickle.loads(data)
return data
class server:
def …Run Code Online (Sandbox Code Playgroud) 我了解加入线程的目的,我在询问资源使用情况。我在这里的特定用例是,我有一个长时间运行的进程,需要生成许多线程,并且在操作过程中,检查它们是否已终止,然后进行清理。主线程等待inotify事件并根据这些事件生成线程,因此它不能在join()调用上阻塞,因为它需要在inotify调用上阻塞。
我知道,例如,使用pthreads时,不加入终止的线程将导致资源泄漏:
PTHREAD_JOIN(3):如果无法与可连接的线程(即未分离的线程)连接,则会生成“僵尸线程”。避免这样做,因为每个僵尸线程都会消耗一些系统资源,并且当累积了足够多的僵尸线程时,将不再可能创建新的线程(或进程)。
但是,Python的文档没有说明这一点,但是它也没有指定,如果期望许多线程在正常操作期间不连接就自行结束,那么可以毫无疑问地忽略join()。
我想知道,我可以简单地获取线程列表并执行以下操作:
threads = [thread for thread in threads if thread.is_alive()]
Run Code Online (Sandbox Code Playgroud)
对于每次检查,还是会泄漏?还是我必须执行以下操作?
alive_threads = list()
for thread in threads:
if thread.is_alive():
alive_threads.append(thread)
else:
thread.join()
threads = alive_threads
Run Code Online (Sandbox Code Playgroud) 我正在学习Python中的线程库。我不明白,如何并行运行两个线程?
这是我的python程序:
没有线程的程序(fibsimple.py)
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
fib(35)
fib(35)
print "Done"
Run Code Online (Sandbox Code Playgroud)
运行时间:
$ time python fibsimple.py
Done
real 0m7.935s
user 0m7.922s
sys 0m0.008s
Run Code Online (Sandbox Code Playgroud)
带有线程的相同程序(fibthread.py)
from threading import Thread
def fib(n):
if n < 2:
return n
else:
return fib(n-1) + fib(n-2)
t1 = Thread(target = fib, args = (35, ))
t1.start()
t2 = Thread(target = fib, args = (35, ))
t2.start()
t1.join()
t2.join()
print "Done"
Run Code Online (Sandbox Code Playgroud)
运行时间:
$ …Run Code Online (Sandbox Code Playgroud) python parallel-processing python-multithreading python-multiprocessing
在编写多线程代码时,我已经阅读了很多关于这个python GIL业务的"糟糕"的内容,但我从未见过一个例子.有人可以给我一个基本的例子,说明GIL在使用线程时何时会出现问题.
谢谢!
我有一个简单的代码,对我正在尝试加速的生成器中的每个项目运行GET请求:
def stream(self, records):
# type(records) = <type 'generator'>
for record in records:
# record = OrderedDict([('_time', '1518287568'), ('data', '5552267792')])
output = rest_api_lookup(record[self.input_field])
record.update(output)
yield record
Run Code Online (Sandbox Code Playgroud)
现在,它在单个线程上运行并且永远需要,因为每个REST调用都会等到上一个REST调用完成.
在使用这个很棒的答案(/sf/answers/1992428651/)之前,我已经在列表中使用Python中的多线程,但是我不确定如何在生成器上重用相同的策略而不是名单.
我得到了一位开发人员的建议,他建议我将生成器分解为100个元素列表,然后关闭池,但我不知道如何从生成器创建这些列表.
我还需要保留原始订单,因为我需要yield record按正确的顺序.
python multithreading generator python-multithreading python-2.7
我有以下问题:给定一个运行 fastapi 的后端,它有一个流端点,用于更新前端,我想在每次调用更新后端状态的函数时发送这些更新(可以是计划的作业或已命中并导致状态更新的不同端点)。
我想要实现的一个简单版本是:
from fastapi import FastAPI
from starlette.responses import StreamingResponse
class State:
def __init__(self):
self.messages = []
def update(self, new_messages):
self.messages = new_messages
# HERE: notify waiting stream endpoint
app = FastAPI()
state = State()
@app.get('/stream')
def stream():
def event_stream():
while True:
# HERE lies the question: wait for state to be update
for message in state.messages:
yield 'data: {}\n\n'.format(json.dumps(message))
return StreamingResponse(event_stream(), media_type="text/event-stream")
Run Code Online (Sandbox Code Playgroud)
我希望它永远运行下去。每次状态更新时,都会event_stream解除阻塞并发送消息。
我看过线程和异步,但我有一种感觉,我缺少一些关于如何在 python 中执行此操作的简单概念。
python python-multithreading server-sent-events python-asyncio fastapi
下面的代码通过将总完成时间返回几乎为零来按预期执行,因为它不会等待线程完成每个作业。
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
return f'Done Sleeping...{seconds}'
executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
Run Code Online (Sandbox Code Playgroud)
但是使用with命令它确实等待:
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]
Run Code Online (Sandbox Code Playgroud)
为什么?with多线程具有这种行为的原因是什么?
我正在创建一个线程管理器类,该类将执行任务作为线程处理并将结果传递给下一个流程步骤。该流程在接收任务的第一次执行时正常工作,但第二次执行失败并出现以下错误:
...python3.8/concurrent/futures/thread.py", line 179, in submit
raise RuntimeError('cannot schedule new futures after shutdown')
RuntimeError: cannot schedule new futures after shutdown
Run Code Online (Sandbox Code Playgroud)
任务来自Cmd.cmdloop用户输入 - 因此,脚本是持久的,不会关闭。相反,run将被多次调用,因为从用户那里收到输入。
我已经实现了一个ThreadPoolExecutor来处理工作负载并尝试按时间顺序收集结果,concurrent.futures.as_completed以便每个项目按照完成的顺序处理到下一步。
run下面的方法非常适合第一次执行,但在第二次执行同一任务(在第一次执行期间成功)时返回错误。
def run ( self, _executor=None, _futures={}, ) -> bool :
task = self.pipeline.get( )
with _executor or self.__default_executor as executor :
_futures = { executor.submit ( task.target.execute, ), }
for future in concurrent.futures.as_completed ( _futures, ) :
print( future.result ( ) )
return True …Run Code Online (Sandbox Code Playgroud) python-multithreading python-3.x threadpoolexecutor concurrent.futures python-3.8
python ×9
python-2.7 ×2
python-3.x ×2
fastapi ×1
generator ×1
gil ×1
kill ×1
pycurl ×1
python-3.8 ×1
subprocess ×1
windows-xp ×1