250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/CPP] 19.03 std::thread와 멀티 쓰레딩 기초 본문

C++/따배C++ 19강 모던 C++ 기능들

[C++/CPP] 19.03 std::thread와 멀티 쓰레딩 기초

polarcompass 2021. 12. 12. 21:28
728x90
#include<iostream>
#include<string>
#include<thread>
#include<chrono>
#include<vector>
#include<mutex>

using namespace std;

// mutual exclusion (상호 배제) 서로 못 건드림.
mutex mtx;

int main()
{
    // 코어 개수 확인
    cout << std::thread::hardware_concurrency() << endl;
    // main thread가 작동하는 메모리 주소
    cout << std::this_thread::get_id() << endl;

    const int n_core = std::thread::hardware_concurrency();

    // main thread id
    cout << "main thread id " << std::this_thread::get_id() << endl;

    // threads 변수 설정 및 개수 설정
    vector<std::thread> my_threads;
    my_threads.resize(n_core);

    // lambda 함수
    for (auto& e : my_threads)
        e = std::thread([](){
            // t1 thread id
            cout << "thread id " << std::this_thread::get_id() << endl;
            while (true){}});
    
    for(auto& e : my_threads )
        e.join();

    
    auto work_func = [](const string& name)
    {
        for( int i=0; i < 5; ++i)
        {
            // 쉬는 시간
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            
            // 위의 계산은 동시에 실행되지만 
            // 출력만 깔끔하게 출력시킬때
            // 멀티 쓰레딩시 중복되는 부분에서 문제해결이 더 중요함
            mtx.lock();
            cout << name << " " << std::this_thread::get_id() << " is working " << i << endl;
            mtx.unlock();
        }
    };

    // 순서대로 실행
    // work_func("jackJack");
    // work_func("Dash");

    // 동시 실행 (멀티 쓰레딩)
    std::thread t1 = std::thread(work_func, "JackJack");
    std::thread t2 = std::thread(work_func, "Dash");

    t1.join();
    t2.join();

    return 0;
}

 

※ OS별 코어수 확인 터미널 명령어

 Mac OS

sysctl -n hw.ncpu

Ubuntu

$ nproc
728x90