lat long
lat long

Reputation: 930

get response or signal when all threads are complete

Using GUI i am copying multiple files. for each file i am starting a thread. Is there is a way with which I can get a signal or response which tells that all the threads are done with their work. I need the response because depending on the response when all threads are done, I want to enable/disable few buttons and check boxes on the GUI.

for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'])
        t.start()

Upvotes: 1

Views: 756

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

You must create a class that inherits from QObject and have custom signals, for example:

def copy_file(source, destination, message, log):
    [...]
    log.finished.emit()

class Logger(QObject):
    finished = pyqtSignal()

self.l = Logger()
for file_name in _src_files:
    if (os.path.exists(_full_file_name)):
        t = Thread(target=file_util.copy_file, args=[_full_file_name, _str_destination_dir, 'update=1'], self.l)
        t.start()
self.l.finished.connect(some_slot)

Example:

import time
from threading import Thread
import sys

from PyQt4.QtGui import *
from PyQt4.QtCore import *

class Logger(QObject):
    finished = pyqtSignal(str)

def myfunc(i, log):
    print("sleeping 5 sec from thread %d" % i)
    time.sleep(5)
    print("finished sleeping from thread %d" % i)
    log.finished.emit("message %d" % i)


class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.l = Logger()
        self.counter_threads = 0
        for i in range(10):
            t = Thread(target=myfunc, args=(i, self.l))
            t.start()
            self.counter_threads += 1
        self.l.finished.connect(self.some_slot)

    def some_slot(self, message):
        print("some_slot: "+ message)
        self.counter_threads -= 1
        if self.counter_threads == 0:
            print("finished all threads")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

Upvotes: 1

Related Questions