亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

類中的p線程函數。

類中的p線程函數。

C++
飲歌長嘯 2019-06-18 15:06:06
類中的p線程函數。假設我有一個類似的類class c {      // ...     void *print(void *){ cout << "Hello"; }}然后我有一個c的向量vector<c> classes; pthread_t t1;classes.push_back(c());classes.push_back(c());現在,我想在c.print();以下是我的問題:pthread_create(&t1, NULL, &c[0].print, NULL);錯誤輸出:無法轉換‘void*(tree_tem:)(無效)“to”無效*()(無效)‘for參數’3‘to’int pline_create(p線程_t*,const p線程_attr_t*,void*()(無效),無效*‘
查看完整描述

3 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

因為C+類成員函數隱藏了this參數傳入。pthread_create()不知道有什么價值this因此,如果您試圖通過將方法轉換為適當類型的函數指針來繞過編譯器,則會出現分段錯誤。您必須使用靜態類方法(它沒有this參數),或者用于引導類的普通函數:

class C{public:
    void *hello(void)
    {
        std::cout << "Hello, world!" << std::endl;
        return 0;
    }

    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }};...C c;pthread_t t;pthread_create(&t, NULL, &C::hello_helper, &c);


查看完整回答
反對 回復 2019-06-18
?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

我最喜歡的處理線程的方法是將它封裝在C+對象中。下面是一個例子:

class MyThreadClass{public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;};

要使用它,只需使用InternalThreadEntry()方法創建MyThreadClass的子類,該方法用于包含線程的事件循環。當然,在刪除線程對象之前,您需要在線程對象上調用WaitForInternalThreadToExit()(當然還需要一些機制來確保線程實際退出,否則WaitForInternalThreadToExit()永遠不會返回)


查看完整回答
反對 回復 2019-06-18
?
12345678_0001

TA貢獻1802條經驗 獲得超5個贊

你得給pthread_create一個與它正在尋找的簽名相匹配的函數。你路過的都沒用。

您可以實現任何您喜歡這樣做的靜態函數,并且它可以引用c在線程中執行你想要的。pthread_create設計為不僅接受函數指針,而且接受指向“上下文”的指針。在這種情況下,您只需將指向c.

例如:

static void* execute_print(void* ctx) {
    c* cptr = (c*)ctx;
    cptr->print();
    return NULL;}void func() {

    ...

    pthread_create(&t1, NULL, execute_print, &c[0]);

    ...}


查看完整回答
反對 回復 2019-06-18
  • 3 回答
  • 0 關注
  • 584 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號