簡體   English   中英

如何從 main ( ) 調用線程成員 function

[英]how to call a thread member function from main ( )

編譯使用線程的程序時出現錯誤。 這是導致問題的部分。如果有人告訴我我是否以正確的方式調用線程 function,那就太好了。

在 main.cpp 中:

int main() 
{
    WishList w;
    boost::thread thrd(&w.show_list);
    thrd.join();
}

在另一個_file.cpp 中:

class WishList{
public:
      void show_list();
}

void WishList::show_list(){
        .
        .
        .
        .
}

我收到以下錯誤

error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function.  Say ‘&WishList::show_list’

/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp: In member function ‘void boost::detail::thread_data<F>::run() [with F = void (WishList::*)()]’:

/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp:61:17: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f (...)’, e.g. ‘(... ->* ((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f) (...)’

編輯:為線程安裝 Boost 庫時遇到問題。 應盡快嘗試此操作

獲取成員 function 的地址的語法是&ClassName::FunctionName ,所以它應該是&WishList::show_list ,但是現在你需要一個 object 來調用 ZC1C425268E68384F1AB4ZA 指針。 最好的(也是最簡單的)是使用boost::bind

#include <boost/bind.hpp>

WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));

與線程無關,這只是“我如何獲得指向成員函數的指針”。 做編譯器說的,說&WishList::show_list 但是您可能還需要傳遞實例指針。

更新:是的,像 Xeo 說的那樣使用bind

關於您的標題:請注意,function 不“屬於線程”。 類不是線程的一部分。 所有線程都訪問相同的 memory - 每個線程都有自己的自動存儲空間,但是 class 定義中沒有任何內容說“這在單獨的線程中”。

暫無
暫無

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

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