使用C++多线程可以进行并行计算,提高执行速率。
在创建thread对象时,要注意如果返回参数是引用类型,如果不使用std::ref
前缀,会发生:
Error C2672 'std::invoke': no matching overloaded function found;
Error C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...) noexcept()' ;
Reference: https://stackoverflow.com/questions/62187098/stdinvoke-no-matching-overloaded-function-found
正确的使用方式:
The arguments to the thread function are moved or copied by value.
If a reference argument needs to be passed to the thread function,
it has to be wrapped (e.g., with std::ref or std::cref).
std::thread my_thread(process_client, std::ref(client));
Example:
#include
void sum(int a, int b, int &c) {
c = a + b;
}
int sum1 = 0;
int sum2 = 0;
std::thread fun1(sum, 1, 2, std::ref(sum1));
std::thread fun2(sum, 3, 4, std::ref(sum2));
fun1.join(); // wait for thread return
fun2.join();
当有其他需求如:加锁和同步等,参考:C++多线程详细讲解
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)