[英]What would be a “Hello, World!” example for “std::ref”?
您应该考虑在函数时使用std::ref
:
std::bind
或std::thread
的构造函数。 std::ref
创建一个行为类似于引用的可复制类型。
这个例子明显地使用了std::ref
。
#include <iostream>
#include <functional>
#include <thread>
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;
// The same applies for std::thread
std::thread( increment, std::ref(i) ).join();
std::cout << i << std::endl;
}
输出:
0
1
2
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
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; }
您希望在各种线程中运行的各种功能共享单个缓冲区对象。 这个例子是从这个优秀的教程( C++11 并发教程 - 第 3 部分:高级锁定和条件变量(Baptiste Wicht) )中窃取的(希望我的归因正确)
// 生产者消费者问题
#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
#include <condition_variable>
using namespace std;
class Buffer {
std::mutex m;
std::condition_variable cv;
std::deque<int> queue;
const unsigned long size = 1000;
public:
void addNum(int num) {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [this]() { return queue.size() <= size; });
queue.push_back(num);
cout << "Pushed " << num << endl;
lock.unlock();
cv.notify_all();
}
int removeNum() {
std::unique_lock<std::mutex> lock(m);
cv.wait(lock, [this]() { return queue.size()>0; });
int num = queue.back();
queue.pop_back();
cout << "Poped " << num << endl;
lock.unlock();
cv.notify_all();
return num;
}
};
void producer(int val, Buffer& buf) {
for(int i=0; i<val; ++i){
buf.addNum(i);
}
}
void consumer(int val, Buffer& buf){
for(int i=0; i<val; ++i){
buf.removeNum();
}
}
int main() {
Buffer b;
std::thread t1(producer, 1000, std::ref(b));
std::thread t2(consumer, 1000, std::ref(b));
t1.join();
t2.join();
return 0;
}
只是在 main 中使用 std::ref ,同时将Buffer
对象作为生产者和消费者中的引用传递。 如果未使用std::ref
则此代码将无法编译。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.