我试图在 python 中同时运行两个长时间运行的操作。它们都对同一数据集进行操作,但不修改它。我发现线程实现的运行速度比简单地一个接一个地运行它们要慢。
我创建了一个简化的示例来展示我所经历的事情。
运行此代码并注释第 46 行(使其执行线程操作),导致我的计算机上的运行时间约为 1:01(分:秒)。我看到两个 CPU 在整个运行时间内以大约 50% 的速度运行。
注释掉第 47 行(导致顺序计算)会导致运行时间约为 35 秒,其中 1 个 CPU 在整个运行时间中被固定为 100%。
两次运行都会导致完成两个完整的计算。
from datetime import datetime
import threading
class num:
def __init__(self):
self._num = 0
def increment(self):
self._num += 1
def getValue(self):
return self._num
class incrementNumber(threading.Thread):
def __init__(self, number):
self._number = number
threading.Thread.__init__(self)
def run(self):
self.incrementProcess()
def incrementProcess(self):
for i in range(50000000):
self._number.increment()
def runThreaded(x, y):
x.start()
y.start()
x.join()
y.join()
def runNonThreaded(x, y):
x.incrementProcess()
y.incrementProcess()
def main():
t = …Run Code Online (Sandbox Code Playgroud) 创建进程池或简单地循环一个进程以创建更多进程之间有什么区别(以任何方式)?
这有什么区别?:
pool = multiprocessing.Pool(5)
pool.apply_async(worker)
pool.join()
Run Code Online (Sandbox Code Playgroud)
和这个?:
procs = []
for j in range(5):
p = multiprocessing.Process(worker)
p.start()
procs.append(p)
for p in procs:
p.join()
Run Code Online (Sandbox Code Playgroud)
池是否更有可能使用更多核心/处理器?
好吧,我是 python 的新手,我很难在 Tkinter 中创建线程,正如你们都知道在 Tkinter 中使用 while 会使它没有响应并且脚本仍在运行。
def scheduler():
def wait():
schedule.run_pending()
time.sleep(1)
return
Hours = ScheduleTest()
if len(Hours) == 0:
print("You need to write Hours, Example: 13:30,20:07")
if len(Hours) > 0:
print("Scheduled: ", str(Hours))
if len(Hours) == 1:
schedule.every().day.at(Hours[0]).do(Jumper)
print("Will jump 1 time")
elif len(Hours) == 2:
schedule.every().day.at(Hours[0]).do(Jumper)
schedule.every().day.at(Hours[1]).do(Jumper)
print("Will jump 2 times")
elif len(Hours) == 3:
schedule.every().day.at(Hours[0]).do(Jumper)
schedule.every().day.at(Hours[1]).do(Jumper)
schedule.every().day.at(Hours[2]).do(Jumper)
print("Will jump 3 times")
while True:
t = threading.Thread(target=wait)
t.start()
return
scheduler()
Run Code Online (Sandbox Code Playgroud)
我尝试过做类似的事情,但它仍然使 tkinter 没有响应,提前致谢。
python multithreading schedule tkinter python-multithreading
我正在尝试了解 Python 3 上的线程。我制作了一个示例代码:
import time
import threading
def myfunction(string,sleeptime,lock,*args):
count = 0
while count < 2:
#entering critical section
lock.acquire()
print(string, " Now sleeping after Lock acquired for ",sleeptime)
time.sleep(sleeptime)
print(string, " Now releasing lock and sleeping again.\n",time.ctime(time.time()))
lock.release()
#exiting critical section
time.sleep(sleeptime)
count+=1
#threading.Thread.daemon=True
if __name__!="__main__":
lock = threading.Lock()
try:
threading.Thread.start(myfunction("Thread Nº 1",2,lock))
threading.Thread.start(myfunction("Thread Nº 2",2,lock))
except:
raise
while 1:pass
Run Code Online (Sandbox Code Playgroud)
它部分起作用。当它到达 时while<2 loop,它返回错误:
Traceback (most recent call last):
File "python", line 22, in <module>
AttributeError: 'NoneType' …Run Code Online (Sandbox Code Playgroud) 问题是我的解决方案是否是一种使用来自另一个线程的数据更新 Tkinter-GUI 的保存和 pythonic 方式?是Lock必需的吗?或者怎么能在Queue这里提供帮助?此示例运行良好,但原始应用程序需要处理复杂得多的数据。
请专注于AsyncioThread.create_dummy_data()最小的工作示例。该示例有两个线程。一个运行Tkinter -mainloop,第二个线程运行asyncio -loop。异步循环模拟获取一些数据并tkinter.Label用这些数据刷新一些数据。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# restrict to Python3.5 or higher because of asyncio syntax
# based on </sf/answers/3354408991/>
from tkinter import *
import asyncio
import threading
import random
class AsyncioThread(threading.Thread):
def __init__(self, asyncio_loop, theWindow):
self.asyncio_loop = asyncio_loop
self.theWindow = theWindow
self.maxData = len(theWindow.varData)
threading.Thread.__init__(self)
def run(self):
self.asyncio_loop.run_until_complete(self.do_data())
async def do_data(self):
""" Creating and starting 'maxData' asyncio-tasks. """ …Run Code Online (Sandbox Code Playgroud) python asynchronous tkinter python-multithreading python-asyncio
您好,我想将日程表与我的 Flask 应用程序集成,因为我需要执行一些日常任务。我在这里找到的他使用线程在后台运行它。然而,当我在我的上尝试时,我无法使用 Ctrl-C 退出我的应用程序,我使用的是 Windows。我很快就会将其部署到 Heroku 上,有什么问题吗?
还有没有更好的、“人性化”的时间表来为 Flask 做一些日常任务?谢谢。
这是我的代码:
from flask import Flask
from datetime import datetime
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import mysql.connector
from mysql.connector import Error
import schedule
import time
from threading import Thread
app = Flask(__name__)
def job():
print("I'm working...")
def run_schedule():
while True:
schedule.run_pending()
time.sleep(1)
@app.route('/')
def homepage():
return '<h1>Hello World!</h1>'
if __name__ == '__main__':
schedule.every(5).seconds.do(job)
sched_thread = Thread(target=run_schedule)
sched_thread.start()
app.run(debug=True, use_reloader=False)
Run Code Online (Sandbox Code Playgroud) 我创建了一个 tkinter GUI,结构如下:
import tkinter as tk
import threading
class App:
def __init__(self, master):
self.display_button_entry(master)
def setup_window(self, master):
self.f = tk.Frame(master, height=480, width=640, padx=10, pady=12)
self.f.pack_propagate(0)
def display_button_entry(self, master):
self.setup_window(master)
v = tk.StringVar()
self.e = tk.Entry(self.f, textvariable=v)
buttonA = tk.Button(self.f, text="Cancel", command=self.cancelbutton)
buttonB = tk.Button(self.f, text="OK", command=threading.Thread(target=self.okbutton).start)
self.e.pack()
buttonA.pack()
buttonB.pack()
self.f.pack()
def cancelbutton(self):
print(self.e.get())
self.f.destroy()
def okbutton(self):
print(self.e.get())
def main():
root = tk.Tk()
root.title('ButtonEntryCombo')
root.resizable(width=tk.NO, height=tk.NO)
app = App(root)
root.mainloop()
main()
Run Code Online (Sandbox Code Playgroud)
我想防止 GUI 在运行函数时冻结(在示例代码中它是确定按钮的功能)。为此,我找到了使用线程模块作为最佳实践的解决方案。但问题是,当我想再次运行代码时,python 返回此回溯:
RuntimeError: threads can only be …Run Code Online (Sandbox Code Playgroud) python user-interface multithreading tkinter python-multithreading
我正在尝试使用线程在后台运行 python http 服务器。我遇到了几个执行以下操作的参考文献:
import threading
import http.server
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler
debug = True
server = http.server.ThreadingHTTPServer((socket.gethostname(), 6666), SimpleHTTPRequestHandler)
if debug:
print("Starting Server in background")
thread = threading.Thread(target = server.serve_forever)
thread.daemon = True
thread.start()
else:
print("Starting Server")
print('Starting server at http://{}:{}'.format(socket.gethostname(), 6666))
server.serve_forever()
Run Code Online (Sandbox Code Playgroud)
当 thread.daemon 设置为True时,程序将完成而不启动服务器(端口 6666 上没有任何运行)。当我将 thread.daemon 设置为False时,它会在前台启动服务器并阻止终端,直到我手动终止它。
关于如何进行这项工作有什么想法吗?
如何与另一个流程共享一个流程的价值?显然我可以通过多线程而不是多处理来做到这一点。多线程对于我的程序来说很慢。
我无法显示我的确切代码,所以我做了这个简单的例子。
from multiprocessing import Process
from threading import Thread
import time
class exp:
def __init__(self):
self.var1 = 0
def func1(self):
self.var1 = 5
print(self.var1)
def func2(self):
print(self.var1)
if __name__ == "__main__":
#multithreading
obj1 = exp()
t1 = Thread(target = obj1.func1)
t2 = Thread(target = obj1.func2)
print("multithreading")
t1.start()
time.sleep(1)
t2.start()
time.sleep(3)
#multiprocessing
obj = exp()
p1 = Process(target = obj.func1)
p2 = Process(target = obj.func2)
print("multiprocessing")
p1.start()
time.sleep(2)
p2.start()
Run Code Online (Sandbox Code Playgroud)
预期输出:
from multiprocessing import Process
from threading import Thread
import …Run Code Online (Sandbox Code Playgroud) python multiprocessing python-multithreading python-3.x python-multiprocessing
我有一个 python 脚本,它连接到多个远程主机并执行 Linux 命令来获取信息。今天的主机数量约为 400 台主机,在这种情况下,我使用 aThreadPoolExecutor来在尽可能短的时间内完成所有任务。
一切顺利,我在 100 秒左右获得了所有数据。问题是我不知道这段时间进程的状态是什么,我想添加一个进度条,当所有的Threads完成时结束。
在我这边,我添加了新代码,使这个进度条成为我的脚本,使用睡眠时间,但正如我所看到的,进度条与线程进程不同步(进度条在线程进程之前几秒钟结束)。
对此有更好的解决方案吗?当这一切运行良好时,我想将这个进度条迁移到 Django 网站中。
这里有我的代码脚本的一部分。
for host in lista_hosts:
res_versiones[host] = val_defecto
# print(res_versiones)
LENGTH = len(lista_hosts) # Number of iterations required to fill pbar
pbar = tqdm(total=LENGTH, desc='consulta_comando') # Init pbar
with ThreadPoolExecutor(200) as executor:
for host in lista_hosts:
host_dns = add_dns_cc.add_dns_concesion(host)
res_command_remote = executor.submit(comando_remoto.comando_remoto_hosts, host_dns, comando, res_versiones, user, clave_rsa, passwd)
time.sleep(0.2)
pbar.update(n=1) # Increments counter
end = time.time() print(f"Runtime of the program is …Run Code Online (Sandbox Code Playgroud) python multithreading python-multithreading python-3.x progress-bar
python ×10
python-3.x ×3
tkinter ×3
schedule ×2
asynchronous ×1
flask ×1
http.server ×1
progress-bar ×1
python-2.7 ×1