Dre*_*ann 83
您应该考虑使用std::ref函数时:
std::bind或者构造函数std::thread.std::ref 是一种行为类似于引用的值类型.
这个例子可以明显地使用std::ref.
#include <iostream>
#include <functional>
void increment( int &x )
{
++x;
}
int main()
{
int i = 0;
// Here, we bind increment to (a copy of) i...
std::bind( increment, i ) ();
// ^^ (...and invoke the resulting function object)
// i is still 0, because the copy was incremented.
std::cout << i << std::endl;
// Now, we bind increment to std::ref(i)
std::bind( increment, std::ref(i) ) ();
// i has now been incremented.
std::cout << i << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
0
1
Run Code Online (Sandbox Code Playgroud)
sba*_*bbi 16
void PrintNumber(int i) {...}
int n = 4;
std::function<void()> print1 = std::bind(&PrintNumber, n);
std::function<void()> print2 = std::bind(&PrintNumber, std::ref(n));
n = 5;
print1(); //prints 4
print2(); //prints 5
Run Code Online (Sandbox Code Playgroud)
std::ref主要用于在使用时封装引用std::bind(当然也可以使用其他用法).
您可能需要std :: ref的另一个地方是将对象传递给线程,您希望每个线程对单个对象进行操作而不是对象的副本.
int main(){
BoundedBuffer buffer(200);
std::thread c1(consumer, 0, std::ref(buffer));
std::thread c2(consumer, 1, std::ref(buffer));
std::thread c3(consumer, 2, std::ref(buffer));
std::thread p1(producer, 0, std::ref(buffer));
std::thread p2(producer, 1, std::ref(buffer));
c1.join();
c2.join();
c3.join();
p1.join();
p2.join();
return 0; }
Run Code Online (Sandbox Code Playgroud)
您希望各种线程中运行的各种函数共享一个缓冲区对象.这个例子是从这个优秀的教程(C++ 11并发教程 - 第3部分:高级锁定和条件变量(Baptiste Wicht) )中窃取的(希望我正确地做了归因)
| 归档时间: |
|
| 查看次数: |
8970 次 |
| 最近记录: |