C8:Asynchronous Programming In Python

本文介绍如何使用多线程技术在Python中更新GUI应用程序的进度条,包括使用单个线程、两个线程以及结合锁定机制的方法。此外,还探讨了如何利用异步操作同时更新多个进度条,并通过上下文管理器来管理资源。

Updating progress bar using thread

Final Result

How to do it?

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()
class MyThread(threading.Thread):
    counter = 0
    def __init__(self, w):
        threading.Thread.__init__(self)
        self.w = w
        self.counter = 0
    def run(self):
        print("Starting " + self.name)
        while self.counter <= 100:
            time.sleep(1)
            w.ui.progressBar.setValue(self.counter)
            self.counter += 10
        print("Exiting "+self.name)
 if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    thread1 = MyThread(w)
    thread1.start()
    w.exec()
    sys.exit(app.exec_())

Updating two progress bars using two threads

Final Result

How to do it?

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()
class MyThread(threading.Thread):
    counter = 0
    def __init__(self,w,ProgressBar):
        threading.Thread.__init__(self)
        self.w = w
        self.counter = 0
        self.progreassBar = ProgressBar
    def run(self):
        print("Staring " + self.name+" n")
        while self.counter <= 100:
            time.sleep(1)
            self.progreassBar.setValue(self.counter)
            self.counter += 10
            print("Exiting " + self.name + "n")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    thread1 = MyThread(w,w.ui.progressBar)
    thread2 = MyThread(w,w.ui.progressBar_2)
    thread1.start()
    thread2.start()
    w.exec()
    thread1.join()
    thread2.join()
    sys.exit(app.exec_())

Updating progress bars using threads bound with a locking mechanism

Final Result

How to do it?

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()
class MyThread(threading.Thread):
    counter = 0
    def __init__(self,w,ProgressBar):
        threading.Thread.__init__(self)
        self.w = w
        self.counter = 0
        self.progreassBar = ProgressBar
    def run(self):
        print("Starting "+ self.name + "n")
        threadLock.acquire()
        while self.counter <= 100:
            time.sleep(1)
            self.progreassBar.setValue(self.counter)
            self.counter += 10
        threadLock.release()
        print("Exiting "+ self.name + "n")
if __name__=="__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    thread1 = MyThread(w,w.ui.progressBar)
    thread2 = MyThread(w,w.ui.progressBar_2)
    threadLock = threading.Lock()
    threads = []
    thread1.start()
    thread2.start()
    w.exec()
    threads.append(thread1)
    threads.append(thread2)
    for t in threads:
        t.join()
    sys.exit(app.exec_())

Updating progress bars simultaneously using asynchronous operations

Final Result

How to do it ?

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.invokeAsync)
        self.show()
    def invokeAsync(self):
        asyncio.ensure_future(self.updt(0.5, self.ui.progressBar))
        asyncio.ensure_future(self.updt(1, self.ui.progressBar_2))
    @staticmethod
    async def updt(delay, progressbar):
        for i in range(101):
            await asyncio.sleep(delay)
            progressbar.setValue(i)
def stopper(loop):
    loop.stop()
if __name__ == "__main__":
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    w = MyForm()
    w.exec()
    with loop:
        loop.run_forever()
    loop.close()
    sys.exit(app.exec_())

Managing resources using context manager

Final Result

How to do it?

class MyForm(QDialog):
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.show()
class MyThread(threading.Thread):
    counter = 0
    def __init__(self,w,ProgressBar):
        threading.Thread.__init__(self)
        self.w = w
        self.counter = 0
        self.progreassBar = ProgressBar
    def run(self):
        print("Starting "+ self.name + "\n")
        with threadLock:
            while self.counter <= 100:
                time.sleep(1)
                self.progreassBar.setValue(self.counter)
                self.counter += 10
        print("Exiting " + self.name + "\n")
if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyForm()
    thread1 = MyThread(w,w.ui.progressBar)
    thread2 = MyThread(w,w.ui.progressBar_2)
    threadLock = threading.Lock()
    threads = []
    thread1.start()
    thread2.start()
    w.exec()
    threads.append(thread1)
    threads.append(thread2)
    for t in threads:
        t.join()
    sys.exit(app.exec_())

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值