c/c++ 多線程 std::call_once的應用


多線程 std::call_once的應用

std::call_once的應用:類成員的延遲初始化,並只初始化一次。和static的作用很像,都要求是線程安全的,c++11之前在多線程的環境下,static好像不是線程安全的,c++11開始,static是線程安全的了。

注意:即使某一個特定的線程里,多次調用了std::call_once,實際的效果是std::call_once里的函數也只被執行一次。

例子:模仿建立數據庫的連接,只有在放生send_data或者receive_data的時候,才去連接數據庫,並且只連接了一次。即使,既調用了send_data也調用了receive_data,但是open_connection只被執行了一次,也就是說數據庫的連接只建立一次就夠了,不管你是要接收,還是要發送。

#include <mutex>
#include <thread>
#include <iostream>

class X{
  int connect_detail;
  std::once_flag connect_init_flag;
  void open_connection(){
    std::cout << "open:" << connect_detail << std::endl;
    //open();
  }

public:
  X(int detail):connect_detail(detail){}
  void send_data(){
    std::call_once(connect_init_flag, &X::open_connection, this);
    //send();
  }
  void receive_data(){
    std::call_once(connect_init_flag, &X::open_connection, this);
    //receive();
  }
};

int main(){
  X x(10);
  x.send_data();
  x.receive_data();
}

github源代碼

執行結果:只打印出一次“open:10”。

結果分析:雖然即調用了send_data,也調用了receive_data,但是open_connection只被執行了一次。

小知識點:下面的&X::open_connection的用法,必須有&和this,雖然open_connection的參數列表為空。因為open_connection是類的成員方法,所以就必須綁定到這個類的某個具體對象上,所以才必須有this和&。&是為了告訴編譯器,這個方法不是類的static方法,而是類的成員方法。

std::call_once(connect_init_flag, &X::open_connection, this);

c/c++ 學習互助QQ群:877684253

本人微信:xiaoshitou5854


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM