C++マルチスレッド学習ノート


レッスン1
  • thread:スレッド、process:プロセス、プロセスはスレッドを含む;
  • t1.join()t 1スレッドの実行が完了してから続行する.
  • t1.detach()はt 1の完了を待たず、他のスレッドが早すぎるとt 1が実行されない可能性がある.

  • レッスン2
  • クラスはスレッドを構築することができる.
  • class Fctor{
    public:
        void operator()(){
            for(int i = 0;i > -100; i--)
                std::cout << "from t1:" << i << std::endl;
            }
    };
    int main(){
    //#######   t1  ,  1##############
        Fctor fct;
        thread t1(fct);
    //######################################
    
    //########   t1  ,  2#############
        thread t1((Fctor()));
    //#####################################
  • d

  • レッスン8呼び出し可能オブジェクトの使用
  • スレッドを作成する2つの方法:
  • std::thread t1(a, 6);
    std::async(std::launch::async, a, 6);
  • サブスレッド
  • を作成
    std::thread t1(a, 6);  //  a       
    std::thread t1(std::ref(a), 6);  //   a       
    std::thread t1(std::move(a), 6);  // a          
    std::thread t4(A(), 6); //       a      
    std::thread t5(foo, 6); //     foo      
    std::thread t6([](int x){return x*x;}, 6); //  lambda  
    
    std::thread t7(&A::f, a, 8, 'w'); //  a            
    std::thread t8(&A::f, &a, 8, 'w'); //   a