簡體   English   中英

pthread_create錯誤:

[英]pthread_create error:

我已經出於個人目的編寫了這段代碼。它將創建一個線程,該線程運行名為event_handler()的例程。例程event_handler將類對象QApplication的實例作為參數並調用其exec()方法。

#include <pthread.h>


void event_handler(void * &obj)
{
    QApplication* app = reinterpret_cast<QApplication*>(&obj);
    app.exec();
}

int main(int argc, char **argv)
{
    pthread_t p1;

    QApplication a(argc, argv);

    pthread_create(&p1, NULL, &event_handler,(void *) &a);

    //do some computation which will be performed by main thread

    pthread_join(*p1,NULL);


}

但是每當我嘗試構建這段代碼時,我都會收到此錯誤

main.cpp:10: error: request for member ‘exec’ in ‘app’, which is of non-class type ‘QApplication*’
main.cpp:34: error: invalid conversion from ‘void (*)(void*&)’ to ‘void* (*)(void*)’
main.cpp:34: error: initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’

我的代碼有什么問題。(請記住,我是該領域的新手,這可能是一個非常愚蠢的錯誤:-))

線程函數必須將void 指針作為其參數,而不是對對象的引用。 您可以稍后將其轉換為正確的指針類型:

void event_handler(void* pointer)
{
    QApplication* app = reinterpret_cast<QApplication*>(pointer);

    app->exec();
}

您還將錯誤的線程標識符傳遞給pthread_join 您不應該在此處使用解引用運算符。


我還建議您研究新的C ++ 11 線程功能 使用std::thread您可以簡單地執行以下操作:

int main()
{
    QApplication app;
    std::thread app_thread([&app]() { app.exec(); });

    // Other code

    app_thread.join();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM