cod*_*her 1 c++ multithreading visual-c++ c++11 visual-studio-2012
这有效:
std::thread t = std::thread(printf, "%d", 1);
Run Code Online (Sandbox Code Playgroud)
这不起作用:
t2 = std::thread(my_thread_func , std::ref(context));
Run Code Online (Sandbox Code Playgroud)
或者
std::thread t1 = std::thread(my_thread_func , context_add);
Run Code Online (Sandbox Code Playgroud)
my_thread_func 定义:
int my_thread_func(long long *context_add)
Run Code Online (Sandbox Code Playgroud)
上下文是一些结构 .. 我正在尝试“按引用传递”
错误:
function call missing argument list;
error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
Run Code Online (Sandbox Code Playgroud)
>>> 编辑 <<<
抱歉混淆...实际上我是在 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);
Run Code Online (Sandbox Code Playgroud)
错误:
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
Run Code Online (Sandbox Code Playgroud)
我的命名空间看起来像:
namespace App1
{
public ref class MainPage sealed
{
public:
MainPage();
public:
MainPage();
int my_thread_func(long long cotext);
..
};
}
Run Code Online (Sandbox Code Playgroud)
<<<< 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);
Run Code Online (Sandbox Code Playgroud)
从这里尝试:http : //en.cppreference.com/w/cpp/thread/thread/thread
最好将您的功能定义为:
int my_thread_func(context& ctx);
Run Code Online (Sandbox Code Playgroud)
然后,您将能够传递对 a 的引用context。如果该函数不应该修改,context那么最好使用:
int my_thread_func(const context& ctx);
Run Code Online (Sandbox Code Playgroud)
然后你可以创建线程,如:
test_context_t context;
/* ... */
std::thread t = std::thread(my_thread_func , std::ref(context));
Run Code Online (Sandbox Code Playgroud)
从您的代码中,您似乎有一个指向context. 您可能需要重新考虑这一点,并像我上面那样使用对象实例。如果上下文作为指针传递给函数,您可能也希望将该指针更改为引用。但是,如果这是不可能的(或不可取的),那么您仍然可以通过执行以下操作来创建线程:
test_context_t* context;
/* ... */
std::thread t = std::thread(my_thread_func , std::ref(*context));
Run Code Online (Sandbox Code Playgroud)
或者,您可以只使用普通指针:
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);
Run Code Online (Sandbox Code Playgroud)