inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

홍정모의 따라하며 배우는 C++

19.6 멀티쓰레딩 예제 (벡터 내적)

lock guard를 사용한 쓰레드 연산결과가 inner_product 함수를 사용한 결과와 다릅니다.

해결된 질문

335

pcm1024zx

작성한 질문수 6

1

오타가 없는 것 같은데 무슨 이유로 다른 값이 나오는지 알수가 없네요. 도움부탁드립니다.

아래는 코드 전문입니다.

#include <iostream>
#include <thread>
#include <mutex>
#include <utility>
#include <future>
#include <vector>
#include <atomic>
#include <chrono>
#include <numeric>
#include <random>
#include <execution>

using namespace std;

auto dotProductFuture(const vector<int>& v0, const vector<int>& v1,
    const unsigned i_start, const unsigned i_end)
{
    int sum = 0;
    for(unsigned i = i_start; i < i_end; ++i)
    {
       sum += v0[i] * v1[i];
    }
    return sum;
}

auto dotProductNaive(const vector<int>& v0, const vector<int>& v1,
    const unsigned i_start, const unsigned i_end, unsigned long long & sum)
{

    for(unsigned i = i_start; i < i_end; ++i)
        sum += v0[i] * v1[i]; 
    return sum;   
}

mutex mtx; 
auto dotProductLock(const vector<int>& v0, const vector<int>& v1,
    const unsigned i_start, const unsigned i_end, unsigned long long & sum)
{
    for(unsigned i = i_start; i < i_end;++i)
    {
        std::scoped_lock lock(mtx); //c++17
        sum += v0[i] * v1[i];
    }
    
}



int main()
{
    const long long n_data = 100'000'000;
    const unsigned n_threads = 4;

    //init vectors
    std::vector<int> v0, v1;
    v0.reserve(n_data);
    v1.reserve(n_data);

    random_device seed;
    mt19937 engine(seed());

    uniform_int_distribution<> uniformDist(1, 10);

    for(long long i = 0; i < n_data; ++i)
    {
        v0.push_back(uniformDist(engine));
        v1.push_back(uniformDist(engine));
    }


    cout << "std::inner_product" << endl;
    {
        const auto sta = chrono::steady_clock::now();

        const auto sum = std::inner_product(v0.begin(), v0.end(), v1.begin(), 0ull);//unsigned long long

        const chrono::duration<double> dur = chrono::steady_clock::now() - sta;

        cout << dur.count() << endl;
        cout << sum << endl;
        cout << endl;
    }


    cout << "Naive" << endl;
    {
        const auto sta = std::chrono::steady_clock::now();

        std::vector<thread> threads;
        threads.resize(n_threads);

        const unsigned n_per_thread = n_data / n_threads;

        unsigned long long sum = 0;
        for(unsigned t = 0; t < n_threads; ++t)
        {
            threads[t] = std::thread(dotProductNaive, std::ref(v0), 
                            std::ref(v1), t*n_per_thread, (t+1)*n_per_thread, std::ref(sum));
        }

        for(unsigned t = 0; t < n_threads; ++t)
            threads[t].join();
        const auto dur = std::chrono::steady_clock::now() - sta;

        cout << dur.count() << endl;
        cout << sum << endl;
        cout << endl;

    }

    cout << "Lock Guard" << endl;
    {
        const auto sta = std::chrono::steady_clock::now();
        
        unsigned long long sum = 0; 
        std::vector<thread> threads;
        threads.resize(n_threads);

        const unsigned n_per_thread = n_data / n_threads;

        
        for(unsigned t = 0; t < n_threads; ++t)
        {
            threads[t] = std::thread(dotProductLock, std::ref(v0), 
                            std::ref(v1), t*n_per_thread, (t+1)*n_per_thread, std::ref(sum));
        }

        // for(unsigned t = 0; t < n_threads; ++t)
        //     threads[t].join();
        const chrono::duration<double> dur = std::chrono::steady_clock::now() - sta;

        cout << dur.count() << endl;
        cout << sum << endl;
        cout << endl;
    }




    return 0; 
}


 

 

c++

답변 2

2

Soobak

안녕하세요, 답변 도우미 Soobak 입니다.

주석으로 처리하신 threads[t].join() 코드라인 부분 때문입니다.

Lock Guard 방식으로 각 연산마다 락을 사용하였기에, 스레드들은 순차적으로 sum 의 값을 갱신하게 됩니다.
그러나, 이 때 주석처리된 thread[t].join() 을 사용하지 않으면, 메인 스레드에서 결과를 출력하기 전에 모든 스레드가 종료되지 않을 수 있습니다.
이로 인해서 일부 스레드의 계산 결과가 최종 결과에 포함되지 않을 수 있게 되어버리는 것입니다.

첨부해주신 코드의 thread[t].join() 부분의 주석을 해제하신 후 확인해보세요.

정상적으로 작동하는 빌드 후 출력 결과 사진을 첨부드립니다.
image

1

pcm1024zx

정신없이 치다보니 주석한것도 못보고 있었네요. 친절한 설명 감사합니다!

강의자료는 어디서 받을 수 있죠?

1

23

2

교재 있나요?

1

140

2

11:11 부근에 Something::temp와 Something::getValue의 앞에 &를 붙이는 이유가 뭔가요? (함수 이름은 포인터(주소)가 아닌가요?)

1

93

3

using namespace std; 선언 후에 std::를 하는 이유가 궁금합니다

1

103

2

cstr직접구현

0

117

3

BubbleSort

1

79

2

숙제 마지막 부분

1

80

2

강의와 똑같이 진행했는데 링킹 에러가 발생합니다.

1

96

2

수업할때 레퍼런스로 사용하는 도서는 어떤 도서인가요??

1

165

2

공변반환형 관련 문의 드립니다.

1

92

2

170강 유니크 포인터에대해 질문있습니다

1

82

1

섹션 5 퀴즈의 답이 이상합니다

1

85

2

이중포인터와 배열이 이해가 안됩니다.

1

159

2

5분 17~5분 34초 객체 잘림 질문

1

80

1

Resource.h 코드 알려주세요

1

74

1

char name[] 배열의 길이와 관련해 일부 궁금점이 생겨서 질문합니다

1

95

2

화면좌측 숫자 보이기

1

116

1

화면 좌측 숫자 보이기

0

68

1

처음 c++ 수강하려는데요. 비주얼스튜디오 2022 다운로드해서 설치하면 되는건가요??

1

139

3

46강 string 버퍼 질문입니다

1

82

2

프로그래머스 수열과 구간 쿼리 2 문제 질문입니다.

1

125

2

[] 범위 검사시 assert 사용 관련 질문

1

92

2

Lecture 클래스 멤버변수 명명 관련

0

93

2

프로그래머스의 대소문자 바꿔서 출력하기 문제를 푸는데요

0

75

1