"Hello, World!"는 무엇입니까? "std :: ref"의 예?
누군가의 기능을 보여주는 간단한 예제를 줄 수 있습니까 std::ref? 튜플이나 데이터 유형 템플릿과 같은 다른 구문 이 없이는 설명 할 수 없는 경우에만 사용되는 예를 의미 std::ref합니다.
std::ref 여기 와 여기 에 대해 두 가지 질문을 찾았 습니다 . 그러나 첫 번째에서는 컴파일러의 버그에 관한 것이고 두 번째에서는 사용 예제에 std::ref포함되지 않으며 std::ref이러한 예제를 복잡하게 이해하는 튜플 및 데이터 유형 템플릿이 포함됩니다.
std::ref함수가 다음과 같은 경우 사용을 고려해야 합니다.
- 값 으로 템플릿 매개 변수를받습니다.
- 또는 의 생성자 와 같은 전달 참조 매개 변수를 복사 / 이동합니다 .std::bindstd::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;
}
산출:
0
1
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 Concurrency Tutorial-Part 3 : Advanced locking and condition variables (Baptiste Wicht) )에서 빼앗 겼습니다.
// Producer Consumer Problem
#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;
}
Just another use of std::ref in main while passing Buffer object as reference in producer and consumer. If std::ref not used then this code will not compile.
참고URL : https://stackoverflow.com/questions/15530460/what-would-be-a-hello-world-example-for-stdref
'Development Tip' 카테고리의 다른 글
| JavaScript 객체를 "잠금"하면 성능상의 이점이 있습니까? (0) | 2020.11.21 | 
|---|---|
| Log.wtf ()는 Log.e ()와 어떻게 다릅니 까? (0) | 2020.11.21 | 
| 속성 라우팅 및 상속 (0) | 2020.11.21 | 
| Dagger와 ButterKnife Android의 차이점 (0) | 2020.11.21 | 
| 명부 (0) | 2020.11.21 |