2015-05-17 90 views
0

我想维护两个函数线程在c + +(Visual Studio支持#包括库),当我运行没有参数的函数它运行良好,但与参数它弹出一个错误。 代码是:执行线程在c + +

void fun(char a[]) 
{} 

int main() 
{ 
    char arr[4]; 
    thread t1(fun); 
    //(Error 1 error C2198: 'void (__cdecl *)(int [])' : too few arguments for call) 

    thread t2(fun(arr));  
    //Error 1 error C2664: std::thread::thread(std::thread &&) throw()' : 
    //cannot  convert parameter 1 from'void' to 'std::thread &&' 
    //Second Error is 2 IntelliSense: no instance of constructor 
    // "std::thread::thread" matches the argument list argument types are: (void 

    return 0; 
} 

帮我处理这个。

+1

你应该检查如何正确传递参数。 http://en.cppreference.com/w/cpp/thread/thread/thread – inf

回答

6

这是std::threadconstructor签名(在facti它是一个模板函数):

template< class Function, class... Args > 
explicit thread(Function&& f, Args&&... args); 

这意味着你必须提供一个Callable(你可以在使用()即任何东西)。 fun是可调用的,因为它是一个函数。但是,表达式fun(arr)不是,因为它表示应用于参数的函数,该参数的类型为void(返回类型为fun)。而且,int表达式thread(fun)你的功能是而不是叫。它被传递给新创建的线程,然后然后执行。如果表达式thread(fun(arr))有效,则在创建新线程之前,将评估表达式fun(arr),并且线程将仅获得fun(arr)的结果,而不是函数本身。

但是C++标准库已经涵盖了你。前面提到的构造函数有一个名为args的参数包(即一个可变长度的参数列表),它允许你为线程函数提供参数。所以你应该使用:

thread t2(fun, arr); 
+0

谢谢。 @ el.pescado –

+0

在switch语句中给出这个错误的线程的初始化。 \t“智能感知:控制转移绕过初始化: 变量”id“(在行157处声明)” –