Start Thread with Button click



  • Hi Guys,

    i have some problems with threading and i hope that sb can help me.

    i have a calculation in a worker class ...
    In my MainWinow i have a button with which the Calculation in the Thread (Worker class) starts..
    Till here everythings works.
    My Problem is that i want that the user can click multiple times on this Button to start new threads without influence the current thread.
    if i right now click multiple times on the Button .. he starts the thread with the same ID... so if the User change some presets in the mainWindow ... it influence all running thread :/

    Has sb any idea how to realize that ?
    Or maybe an idea ... How can i ask how Mama Threads are running ?

     thread = new QThread();
        worker = new Worker();
    
        worker->moveToThread(thread);  <-- This is the Problem he creates all the time the same thread :/ how can i program this generic that he start a new Thread with a new ID ? 
      
    
        thread->start();
    
    


  • @BadHombre
    Your worker and thread are class members? That's not good.

    Why do you think that it's always the same thread?

    basic example:
    threadex.h

    #ifndef THREADEX_H
    #define THREADEX_H
    #include <QThread>
    #include <QDebug>
    class ThreadEx : public QThread
    {
        Q_OBJECT
    public:
        explicit ThreadEx(QObject *parent = nullptr) :
            QThread(parent)
        {
            qDebug() << "thread: " << this << "created in: " << QThread::currentThread() << "which has id: "  << QThread::currentThreadId();
    
        }
        ~ThreadEx()
        {
            qDebug() << "thread: " << this << "deleted in: " << QThread::currentThread() << "which has id: "  << QThread::currentThreadId();
        }
    };
    #endif // THREADEX_H
    

    main.cpp

    ThreadEx *thread1 = new ThreadEx;
    Worker *worker1 = new Worker;
    worker1->moveToThread(thread1);
    
    ThreadEx *thread2= new ThreadEx;
    Worker *worker2 = new Worker;
    worker2->moveToThread(thread2);
    
    

    Output

    thread:  ThreadEx(0x115fd00) created in:  QThread(0x113fb18) which has id:  0x1920
    thread:  ThreadEx(0x115fda8) created in:  QThread(0x113fb18) which has id:  0x1920
    

    thread1 and thread2 are different threads, but they live in the same thread (main thread in this case) as QThread is a QObject, and every QObject has a thread affinity



  • It is indeed creating different thread object. You are also moving the worker to new thread. I did not see any connection with started() signal from Thread object. QThread emits started() signal, when you call QThread.start() method. What are you doing the started().. signal ? Slot should be connected to started() signal. After this slot will be executed in different thread.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.