我正在尝试并行绘图以更快地完成大批量作业.为此,我为我计划制作的每个剧情开始一个主题.
我曾希望每个线程都能完成它的绘图并自行关闭(据我所知,当Python通过run()中的所有语句时,它会关闭线程).下面是一些显示此行为的代码.
如果创建图形的行已注释掉,则按预期运行.另一个看似合情合理的消息是,当你只生成一个线程时,它也会按预期运行.
import matplotlib.pyplot as plt
import time
import Queue
import threading
def TapHistplots():
## for item in ['str1']:
# # it behaves as expected if the line above is used instead of the one below
for item in ['str1','str2']:
otheritem = 1
TapHistQueue.put((item, otheritem))
makeTapHist().start()
class makeTapHist(threading.Thread):
def run(self):
item, otheritem = TapHistQueue.get()
fig = FigureQueue.get()
FigureQueue.put(fig+1)
print item+':'+str(fig)+'\n',
time.sleep(1.3)
plt.figure(fig) # comment out this line and it behaves as expected
plt.close(fig)
TapHistQueue = Queue.Queue(0)
FigureQueue = Queue.Queue(0) …Run Code Online (Sandbox Code Playgroud) t1=threading.Thread(target=self.read())
print "something"
t2=threading.Thread(target=self.runChecks(), args=(self))
Run Code Online (Sandbox Code Playgroud)
self.read无限期地运行,所以程序将无法到达该print行.没有打电话t1.start()怎么可能呢?(即使我打电话给它,它会开始运行并继续下一行,不应该吗?)
我想在python中创建一个:memory:database,并从不同的线程访问它.基本上是这样的:
class T(threading.Thread):
def run(self):
self.conn = sqlite3.connect(':memory:')
# do stuff with the database
for i in xrange(N):
T().start()
Run Code Online (Sandbox Code Playgroud)
并让所有连接引用同一个数据库.
我知道传递check_same_thread=True给connect函数并在线程之间共享连接,但是如果可能的话,我希望避免这样做.谢谢你的帮助.
编辑:纠正错字.我最初说"将所有连接引用到同一个线程"将线程替换为数据库.
我试图并行下载整个ftp目录.
#!/usr/bin/python
import sys
import datetime
import os
from multiprocessing import Process, Pool
from ftplib import FTP
curYear=""
remotePath =""
localPath = ""
def downloadFiles (remotePath,localPath):
splitted = remotePath.split('/');
host= splitted[2]
path='/'+'/'.join(splitted[3:])
ftp = FTP(host)
ftp.login()
ftp.cwd(path)
filenames = ftp.nlst()
total=len(filenames)
i=0
pool = Pool()
for filename in filenames:
local_filename = os.path.join(localPath,filename)
pool.apply_async(downloadFile, (filename,local_filename,ftp))
#downloadFile(filename,local_filename,ftp);
i=i+1
pool.close()
pool.join()
ftp.close()
def downloadFile(filename,local_filename,ftp):
file = open(local_filename, 'wb')
ftp.retrbinary('RETR '+ filename, file.write)
file.close()
def getYearFromArgs():
if len(sys.argv) >= 2 and sys.argv[1] == "Y": …Run Code Online (Sandbox Code Playgroud) 我正在运行一个解析大量数据的python方法.由于它是时间密集的,我想在一个单独的线程上异步运行它,以便用户仍然可以访问网站/ UI.
如果用户退出站点或继续在服务器上运行,是否使用"来自线程导入线程"模块的线程终止?
使用Celery与仅仅使用线程模块这样的优势有什么好处?
我试图在python中使用Queue,这将是多线程的.我只是想知道我使用的方法是否正确.如果我正在做一些多余的事情或者如果有更好的方法我应该使用.
我试图从表中获取新请求,并使用某些逻辑来安排它们执行某些操作,如运行查询.
所以这里从主线程我为队列生成一个单独的线程.
if __name__=='__main__':
request_queue = SetQueue(maxsize=-1)
worker = Thread(target=request_queue.process_queue)
worker.setDaemon(True)
worker.start()
while True:
try:
#Connect to the database get all the new requests to be verified
db = Database(username_testschema, password_testschema, mother_host_testschema, mother_port_testschema, mother_sid_testschema, 0)
#Get new requests for verification
verify_these = db.query("SELECT JOB_ID FROM %s.table WHERE JOB_STATUS='%s' ORDER BY JOB_ID" %
(username_testschema, 'INITIATED'))
#If there are some requests to be verified, put them in the queue.
if len(verify_these) > 0:
for row in verify_these:
print "verifying : %s" …Run Code Online (Sandbox Code Playgroud) 我有很多泡菜文件。目前我循环阅读它们,但这需要很多时间。我想加快速度,但不知道如何做到这一点。
多处理不起作用,因为为了将数据从子进程传输到主进程数据需要序列化(腌制)和反序列化。
由于 GIL,使用线程也无济于事。
我认为解决方案是一些用 C 编写的库,它需要读取文件列表,然后运行多个线程(没有 GIL)。周围有这样的东西吗?
更新 回答您的问题:
pandas.Series对象,但预先不知道 dtype我正在处理的当前Python应用程序需要使用1000多个线程(Pythons线程模块).并不是说任何单个线程都在最大cpu周期工作,这只是我正在创建的Web服务器负载测试应用程序.IE模拟200个firefox客户端,他们都渴望进入Web服务器并下载小型Web组件,基本上模拟人类在几秒钟内操作,而不是微秒.
所以,我正在阅读各种主题,例如"在Linux/Windows上支持python的线程数等等,我看到了很多不同的答案.一位用户表示,所有内存和Linux内核默认只留出8Meg用于线程,如果超过该线程,则线程开始被内核杀死.
有人说这对CPython来说不是问题,因为无论如何只有一个线程一次运行(因为GIL)所以我们可以指定一个庞大的线程??? 这有什么实际的真相?
python multithreading thread-safety threadpool python-multithreading
阅读http://bugs.python.org/msg160297,我可以看到一个由Stephen White编写的简单脚本,它演示了python线程如何在这个异常中出错
Exception AttributeError: AttributeError("'_DummyThread' object has no attribute '_Thread__block'",) in <module 'threading'
Run Code Online (Sandbox Code Playgroud)
鉴于Stephen White的源代码(http://bugs.python.org/file25511/bad-thread.py),
import os
import thread
import threading
import time
def t():
threading.currentThread() # Populate threading._active with a DummyThread
time.sleep(3)
thread.start_new_thread(t, ())
time.sleep(1)
pid = os.fork()
if pid == 0:
os._exit(0)
os.waitpid(pid, 0)
Run Code Online (Sandbox Code Playgroud)
我们如何重新编写它以便解决此错误?
几个星期前我开始用Python编程,并试图使用Semaphores同步两个简单的线程,用于学习目的.这是我得到的:
import threading
sem = threading.Semaphore()
def fun1():
while True:
sem.acquire()
print(1)
sem.release()
def fun2():
while True:
sem.acquire()
print(2)
sem.release()
t = threading.Thread(target = fun1)
t.start()
t2 = threading.Thread(target = fun2)
t2.start()
Run Code Online (Sandbox Code Playgroud)
但它一直打印只有1.如何对照片进行内部缩放?
python ×10
celery ×1
matplotlib ×1
python-2.7 ×1
queue ×1
semaphore ×1
sqlite ×1
threadpool ×1