SYeonni Study Room

간단한 쓰레드 구현 본문

언어/C++

간단한 쓰레드 구현

SYeonni 2022. 7. 22. 10:09

c++ 17 

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <string_view>

int TestFunction(int count){
    int result = 0;
    std::vector<int> Temp = {};
    for(int i = 0; i < count; i++){
        Temp.push_back(i);
    }
    for(auto &iter :  Temp ) {
        result += iter;
    }
    return result;
}

std::mutex _mutex;

void thread_function(int count, std::string_view Num){
    int Result = 0;

    for(int i = 0; i<count; i++){
        _mutex.lock();
        Result +=  TestFunction(i);
        _mutex.unlock();
        std::cout << Num << " : " <<  Result << std::endl;
    }
}

int main() {

/*    auto lambda = [](int i , int j){return i+j ;};
    std::cout <<lambda(3,4)<<std::endl;*/

    std::thread t1(thread_function,rand()%10, "1st thread");
    std::thread t2(thread_function,rand()%10, "2st thread");
    std::thread t3(thread_function,rand()%10, "3st thread");

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

   return 0;
}

 

728x90

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

Consol창 1개 더 띄우기  (0) 2022.08.15
string_view  (0) 2022.07.22
decltype 키워드 사용  (0) 2022.07.19
내가 제일 좋아하는 auto ... ♥  (0) 2022.07.18
백준 2588번 문제  (0) 2022.06.09