1. 程式人生 > >linux下c++使用pthread_create時需要呼叫類成員

linux下c++使用pthread_create時需要呼叫類成員

前幾天自己寫程式碼的時候,需要用到多執行緒的東西,但是由於需要執行的函式是一個類的成員,沒有辦法進行呼叫(將函式填入之後,編譯報錯。大致是引數格式不正確之類的提示),後來在網上查找了一些解決的辦法,做下記錄。

主要思路:
多執行緒可以直接呼叫靜態的函式,在通過把類的指標傳進去的方法訪問類內部的成員變數。

#include <iostream>
#include <thread>
using namespace std;




class TestClass
{
    public:
        TestClass();
        ~TestClass();
        void
thread_handler() { cout << "handler" <<endl; } }; int main(int argc, char const *argv[]) { pthread_t threadnum = 0; TestClass * foo = new TestClass(); pthread_create(&threadnum,NULL,foo->thread_handler,NULL); while(1); return 0; }

出現以下錯誤:

test.cpp:31:57: error: argument of type ‘void (TestClass::)()’ does not match ‘void* ()(void)’

可以通過這樣修改

#include <iostream>
#include <thread>
using namespace std;




class TestClass
{
    public:
        TestClass()
        {}
        ~TestClass();
        void thread_handler()
        {
            cout
<< "handler" <<endl; } static void * thread_run(void* tmp) { TestClass *p = (TestClass *)tmp; p->thread_handler(); } }; int main(int argc, char const *argv[]) { pthread_t threadnum = 0; TestClass * foo = new TestClass(); pthread_create(&threadnum,NULL,TestClass::thread_run,foo); while(1); return 0; }

程式中的程式碼寫的隨意,意思大概有了就好。
如果有其他更好的方法,歡迎一起學習討論。