Pass multiple arguments into std::thread

前端 未结 3 904
礼貌的吻别
礼貌的吻别 2020-12-05 09:10

I\'m asking the library in C++11 standard.

Say you have a function like:

void func1(int a, int b, ObjA c, ObjB d){
             


        
3条回答
  •  伪装坚强ぢ
    2020-12-05 09:57

    You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

    This is how it should be done.

    std::thread t(func1,a,b,c,d);
    t.join();  
    

    You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

提交回复
热议问题