如果你在類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"
這兩種方法都有各自的優缺點,你可以根據實際需求和設計考慮選擇適合的方法。