如果你在类A中使用pthread_create创建了线程B,而线程B需要与类A进行通信,你可以考虑以下两种方法:
使用回调函数: 在创建线程B时,通过参数传递一个回调函数,该回调函数可以在线程B中执行,并在完成任务后调用类A中的相应方法。这就需要确保回调函数中不会访问已经销毁的对象,因此线程B需要知道何时可以安全地调用回调函数。
#include <iostream>
#include <pthread.h>class A {
public:A() {// 创建线程Bpthread_create(&threadB, nullptr, threadBFunction, this);}~A() {// 等待线程B结束pthread_join(threadB, nullptr);}void handleWorkerFinished(const std::string &message) {std::cout << "A: Worker finished with message: " << message << std::endl;}private:pthread_t threadB;static void *threadBFunction(void *data) {A *a = static_cast<A *>(data);// 在线程B中执行任务// 完成后调用回调函数a->handleWorkerFinished("Work in thread B is done!");pthread_exit(nullptr);}
};int main() {A objA;// 主线程继续执行其他任务...return 0;
}
使用信号和槽: 在线程B中,你可以通过QMetaObject::invokeMethod调用类A中的槽函数。这种方法可能需要考虑线程安全性,并确保在线程B调用槽函数时,类A对象仍然有效。
#include <iostream>
#include <pthread.h>
#include <QCoreApplication>
#include <QObject>class A : public QObject {Q_OBJECTpublic:A() {// 创建线程Bpthread_create(&threadB, nullptr, threadBFunction, this);}~A() {// 等待线程B结束pthread_join(threadB, nullptr);}public slots:void handleWorkerFinished(const QString &message) {std::cout << "A: Worker finished with message: " << message.toStdString() << std::endl;}private:pthread_t threadB;static void *threadBFunction(void *data) {A *a = static_cast<A *>(data);// 在线程B中执行任务// 完成后调用槽函数QMetaObject::invokeMethod(a, "handleWorkerFinished", Qt::QueuedConnection, Q_ARG(QString, "Work in thread B is done!"));pthread_exit(nullptr);}
};int main(int argc, char *argv[]) {QCoreApplication a(argc, argv);A objA;// 主线程继续执行其他任务...return a.exec();
}#include "main.moc"
这两种方法都有各自的优缺点,你可以根据实际需求和设计考虑选择适合的方法。