[英]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.