What would be a “Hello, World!” example for “std::ref”?

后端 未结 4 2049
星月不相逢
星月不相逢 2021-01-30 01:54

Can somebody give a simple example which demonstrates the functionality of std::ref? I mean an example in which some other constructs (like tuples, or data type tem

4条回答
  •  攒了一身酷
    2021-01-30 02:50

    Another place where you may need std::ref is when passing objects to threads where you want each thread to operate on the single object and not a copy of the object.

    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; }
    

    where you wish various functions running in various threads to share a single buffer object. This example was stolen from this excellent tutorial ( C++11 Concurrency Tutorial - Part 3: Advanced locking and condition variables (Baptiste Wicht) ) (hope I did the attribution correctly)

提交回复
热议问题