其他分享
首页 > 其他分享> > FetchData_Background_decorator

FetchData_Background_decorator

作者:互联网

from PyQt5.Qt import QThread, QThreadPool, QRunnable, QObject, QWidget, QApplication, QPushButton, QGridLayout, QTextEdit, pyqtSignal, QTextCursor
import sys
import time
from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot
from PyQt5.QtWidgets import *
from concurrent.futures import *
from multiprocessing import *
import threading
from PyQt5.QtCore import *

g_executor = ProcessPoolExecutor()
g_queues = None
g_threadids = []
g_pool = None
mutex = QMutex()

def getData_med(v=10, *args, **kargs):
    # time.sleep(v/2.0)
    kargs['que'].put(v*2) #进度
    return v

class Task(QRunnable):
    def __init__(self, sigProcessRate, sigDataReturn, fn, *args, **kargs):
        super(Task, self).__init__()
        self.sigProcessRate = sigProcessRate
        self.sigDataReturn = sigDataReturn
        self.fn = fn
        self.args = args
        self.kargs = kargs

    def run(self):
        # global g_threadids
        threadname = threading.currentThread().name
        threadname not in g_threadids and g_threadids.append(threadname)
        self.kargs['que'] = g_queues[g_threadids.index(threadname)]

        r = g_executor.submit(self.fn, *self.args, **self.kargs)
        r.add_done_callback(self.cb)
        while True:
            v = self.kargs['que'].get()
            if v > 99:
                break
            self.sigProcessRate.emit(v)
        # mutex.lock()
        # print("runable end {}".format(threading.currentThread().name), self.kargs['que'])
        # mutex.unlock()
    def cb(self,r):
        self.kargs['que'].put(100)
        self.sigDataReturn.emit([r.result()])


class FetchData_Background_decorator(QObject):
    sigDataReturn = pyqtSignal(list)
    sigProcessRate = pyqtSignal(int)
    def __init__(self, fn, *args, **kargs):
        super(FetchData_Background_decorator, self).__init__()
        self.initContext()
        g_pool.start(Task(self.sigProcessRate, self.sigDataReturn, fn, *args, **kargs))

    @staticmethod
    def initContext():
        mutex.lock()
        global g_pool
        if g_pool is None:
            g_pool = QThreadPool()
            g_pool.globalInstance()
            g_pool.setMaxThreadCount(2)
            global g_queues
            g_queues = [Manager().Queue(), Manager().Queue(), Manager().Queue(), Manager().Queue()]
        mutex.unlock()
def p(s,v):
    mutex.lock()
    print(s,v)
    mutex.unlock()

if __name__ == '__main__':
    app = QApplication(sys.argv)

    win = {}
    for i in range(4):
        win[str(i)] = FetchData_Background_decorator(getData_med, v=i)
        win[str(i)].sigProcessRate.connect(lambda v: p('ProcessRate', v))
        win[str(i)].sigDataReturn.connect(lambda v: p('DataReturn', v))

    sys.exit(app.exec())

 

标签:__,kargs,self,mutex,Background,import,sigDataReturn,FetchData,decorator
来源: https://www.cnblogs.com/liuguoyao514257665/p/14396844.html