C++/Thread

클래스로 Thread 구현

(26020)

두개의 로봇 이름을 각각 "R2D2" 와 "U-3PO"라 하고 두개의 로본이 동시에 실행되도록 스레드 두개를 실행하라.


#include <iostream>
#include <unistd.h>
#include <thread>
using namespace std;
class Robot{
    public:
        Robot(string name) :name_(name){
        }
        void operator () (){
            run();
        }
        void run(){
            for (auto i=1; i<=10; i++){
                usleep(100000);
                cout <<  name_ << " walks "
                     << i << " steps" << endl;
            }
        }
    protected:
        string name_;
};

int main(){
        Robot r1("R2D2");
        Robot r2("U-2P0");
        std::thread first(r1);
        std::thread second(r2);
        first.join();
        second.join();
        return 0;
}

'C++ > Thread' 카테고리의 다른 글

Thread 기초  (0) 2021.01.27