[英]Constructing a std::thread with a function
這有效:
std::thread t = std::thread(printf, "%d", 1);
這不起作用:
t2 = std::thread(my_thread_func , std::ref(context));
要么
std::thread t1 = std::thread(my_thread_func , context_add);
my_thread_func定義:
int my_thread_func(long long *context_add)
上下文是一些結構..我正在嘗試'通過引用傳遞'
錯誤:
function call missing argument list;
error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
>>>編輯<<<
很抱歉混淆......實際上我是在公共MainPage中定義my_thread_func,所以我不能使用原生類型因此我認為值得長期嘗試並給它地址。
/* test data types, context for thread function, in .cpp (not in namespace) */
typedef struct _test_context
{
HANDLE hHandle;
unsigned int flag;
}test_context_t;
test_context_t *context;
//Do something with its member
context_add = (long long *)context;
std::thread t2 = std::thread(sem_waiting_thread, context_add);
錯誤:
error C3867: 'App1::MainPage::my_thread_func': function call missing argument list; use '&App1::MainPage::my_thread_func' to create a pointer to member
error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
我的命名空間如下:
namespace App1
{
public ref class MainPage sealed
{
public:
MainPage();
public:
MainPage();
int my_thread_func(long long cotext);
..
};
}
<<<< EDIT 2 >>>我現在好奇..這個簡單的也行不通!
void f1(int n)
{
for(int i=0; i<5; ++i) {
// Print n
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
.
.
.
int n=0;
std::thread t2(f1, n+1); (//This didn't work,same error!)
.
.
.
but this worked!
std::thread t2;
.
.
.
t2= std::thread (f1, n+1);
試試這里: http : //en.cppreference.com/w/cpp/thread/thread/thread
最好將您的函數定義為:
int my_thread_func(context& ctx);
然后,您就可以將引用傳遞給context
。 如果該函數不應該修改context
那么最好使用:
int my_thread_func(const context& ctx);
然后你可以創建如下的線程:
test_context_t context;
/* ... */
std::thread t = std::thread(my_thread_func , std::ref(context));
從你的代碼看,你似乎有一個指向context
的指針。 您可能想重新考慮這一點,並像上面一樣使用對象實例。 如果將上下文作為指針傳遞給函數,您可能也希望將該指針更改為引用。 但是如果那是不可能的(或者是可取的)那么你仍然可以通過這樣做來創建線程:
test_context_t* context;
/* ... */
std::thread t = std::thread(my_thread_func , std::ref(*context));
或者,您可以使用普通指針:
int my_thread_func(context* ctx); // notice the different function's signature
test_context_t* context;
/* ... */
std::thread t = std::thread(my_thread_func , context);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.