gpt4 book ai didi

python - 如何在 Python 中暂停多处理进程?

转载 作者:行者123 更新时间:2023-12-03 20:23:37 30 4
gpt4 key购买 nike

我希望用户能够在启动后的任何给定时间暂停多处理的执行。如何实现?

我的代码是:

# -*- coding: utf-8 -*-
from PySide import QtCore, QtGui
from Ui_MainWindow import Ui_MainWindow
from queue import Queue
import sys
import multiprocessing, os, time

def do_work():
print ('Work Started: %d' % os.getpid())
time.sleep(1)
return 'Success'

def manual_function(job_queue, result_queue):
while not job_queue.empty():
try:
job = job_queue.get(block=False)
result_queue.put(do_work())
except Queue.Empty:
pass

class Worker(QtCore.QThread):
def __init__(self,name):
QtCore.QThread.__init__(self)
self.name = name
self.pause = False

def run(self):
job_queue = multiprocessing.Queue()
result_queue = multiprocessing.Queue()

for i in range(1000):
job_queue.put(None)

self.workers = []
for i in range(6):
tmp = multiprocessing.Process(target=manual_function, args=(job_queue, result_queue))
tmp.start()
self.workers.append(tmp)

def paused(self):
'''
pause / resumme ?????????????????????????
'''

def stop(self):
for worker in self.workers:
print ("end")
worker.terminate()
worker.join()


class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.connect(self.ui.actionStart, QtCore.SIGNAL('triggered()'),self.start)
self.connect(self.ui.actionStop, QtCore.SIGNAL('triggered()'),self.stop)
self.connect(self.ui.actionPause, QtCore.SIGNAL('triggered()'),self.pause)

def pause(self):
self.work.paused()

def stop(self):
self.work.stop()

def start(self):
self.threads = []
for tName in range(1):
self.work = Worker("Thread-%s"%tName)
self.threads.append(self.work)
self.work.start()

if __name__ == "__main__":
app = QtGui.QApplication (sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

如何在 Python 中暂停按钮单击多处理进程?

最佳答案

使用一个简单的标志作为共享内存,以确定生成的进程是否运行。看一个小例子。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from multiprocessing import Process, Value
from time import sleep

def do_work():
print("Working...")
sleep(1)

def worker(run):
while True:
if run.value:
do_work()

if __name__ == "__main__":
run = Value("i", 1)
p = Process(target=worker, args=(run,))
p.start()
while True:
raw_input()
run.value = not run.value

我分享了一个 Value 的实例进程之间。按 Enter 暂停或恢复生成的进程。

这适用于 Python 2,您应该指出您正在运行哪个版本。

希望能帮助到你。

关于python - 如何在 Python 中暂停多处理进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28812011/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com