线程在c++中的实现
Implementation of Threads in c++
我试图在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();
}
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的