Насмешка и глушение с транспортиром

Некоторые пользователи уже дали свой ответ и объяснили это очень хорошо.

Я хотел бы добавить еще несколько вещей, связанных с потоком.

  1. Как работать с функтором и нить. Пожалуйста, обратитесь к приведенному ниже примеру.
  2. Поток будет создавать свою собственную копию объекта при прохождении объекта.
    #include<thread>
    #include<Windows.h>
    #include<iostream>
    
    using namespace std;
    
    class CB
    {
    
    public:
        CB()
        {
            cout << "this=" << this << endl;
        }
        void operator()();
    };
    
    void CB::operator()()
    {
        cout << "this=" << this << endl;
        for (int i = 0; i < 5; i++)
        {
            cout << "CB()=" << i << endl;
            Sleep(1000);
        }
    }
    
    void main()
    {
        CB obj;     // please note the address of obj.
    
        thread t(obj); // here obj will be passed by value 
                       //i.e. thread will make it own local copy of it.
                        // we can confirm it by matching the address of
                        //object printed in the constructor
                        // and address of the obj printed in the function
    
        t.join();
    }
    

Другой способ достижения того же:

void main()
{
    thread t((CB()));

    t.join();
}

Но если вы хотите передать объект по ссылке, используйте синтаксис ниже:

void main()
{
    CB obj;
    //thread t(obj);
    thread t(std::ref(obj));
    t.join();
}
30
задан Bastien Caudan 18 February 2014 в 18:43
поделиться