线程在c++中的实现

Implementation of Threads in c++

本文关键字:实现 c++ 线程      更新时间:2023-10-16

我试图在c++(Visual Studio支持#include库(中用线程维护两个函数,当我在没有参数的情况下运行函数时,它运行得很好,但有参数时会弹出一个错误。代码为:

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;
}

帮我处理这个。

这是std::thread构造函数的签名(实际上是一个模板函数(:

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

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

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

thread t2(fun, arr); 

看看这个例子:

https://mockstacks.com/Cpp_Threading

#include <string>
#include <iostream>
#include <thread>
using namespace std;
// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}
int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");
    // Do other things...
    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}