gpt4 book ai didi

multithreading - QT:从其他线程运行独立线程

转载 作者:行者123 更新时间:2023-12-04 06:42:04 26 4
gpt4 key购买 nike

让我举个例子。

class B : public  QThread {
public:
void run() {
}
};

class A : public QThread {
public:
void run() {
b1.start(); b2.start();
}
protected:
B b1, b2;
};

我希望 A::b1 和 A::b2 作为完全独立的线程运行,而不是共享父线程 (A) 的资源。有没有办法指定主线程为b1和b2的父线程?

我也看过 QThreadPool 和 QRunnable,我不明白,怎么可能管理线程池的所有可运行对象(例如,停止其中一个,然后再运行它)。

最佳答案

子类QThreadwrong way在 Qt 中创建线程。 QObject 提供函数 moveToThread它只允许您更改对象及其子对象的线程关联。

Changes the thread affinity for this object and its children. The object cannot be moved if it has a parent. Event processing will continue in the targetThread.

To move an object to the main thread, use QApplication::instance() to retrieve a pointer to the current application, and then use QApplication::thread() to retrieve the thread in which the application lives.

所以你应该做的是从 QObject 而不是 QThread 继承并更改你的运行函数以将 B 对象移动到其他线程。

示例代码(未经测试)

class B : public  QObject {
Q_OBJECT
public:
void run() {
}
};

class A : public QObject {
Q_OBJECT
public:
void run() {
b1Thread = new QThread;
b2Thread = new QThread;
b1.moveToThread(b1Thread);
b2.moveToThread(b2Thread);

b1.run();
b2.run();
}
protected:
B b1, b2;
private:
QThread* b1Thread, b2Thread; // Delete them in the destructor.
};

您可以在 main.cpp 中构建线程并将它们作为参数传递给 B 类。

注意以下关于moveToThread

this function can only "push" an object from the current thread to another thread, it cannot "pull" an object from any arbitrary thread to the current thread.

关于multithreading - QT:从其他线程运行独立线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8063434/

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