Leetcode

LeetCode 1114. Print in Order [C++/ atomic]

치킨먹고싶어요 2022. 6. 3. 15:28

https://leetcode.com/problems/print-in-order/

 

Print in Order - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

코드 : 

class Foo {
    atomic<int> turn = 1;
public:
    Foo() {
    }
 
    void first(function<void()> printFirst) {
        while (turn <= 1
            if (turn == 1) {
                printFirst();
                turn++;
            }
    }
 
    void second(function<void()> printSecond) {
        while (turn <= 2
            if (turn == 2) {
                printSecond();
                turn++;
            }
    }
 
    void third(function<void()> printThird) {
         while (turn <= 3
            if (turn == 3) {
                printThird();
                turn++;
            }
    }
};
cs

해설 :

 

class Foo {
    atomic<int> turn = 1// 쓰레드에도 영향을 받지 않는 원자적 정수를 선언합니다.
public:
    Foo() {
    }
 
    void first(function<void()> printFirst) {
        while (turn <= 1// 1이 올 때 까지 대기 합니다
            if (turn == 1) {
                printFirst();
                turn++;
            }
    }
 
    void second(function<void()> printSecond) {
        while (turn <= 2// 2가 올 때 까지 대기합니다
            if (turn == 2) {
                printSecond();
                turn++;
            }
    }
 
    void third(function<void()> printThird) {
         while (turn <= 3// 3이 올 떄 까지 
            if (turn == 3) {
                printThird();
                turn++;
            }
    }
};
cs