Thuta Learning
C++
AdvancedProgrammingအခြေခံ

Concurrency with std::jthread

C++သင်ခန်းစာ 2935 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • std::jthread ကို ဖန်တီးပြီး std::thread နဲ့ မတူဘဲ destructor မှာ ဘာကြောင့် အလိုအလျောက် join လုပ်လဲ ရှင်းပြနိုင်ဖို့
  • Data race ဆိုတာ ဘာလဲ ဖော်ပြပြီး မမျှဝေခြင်း၊ std::atomic၊ std::mutex ဆိုတဲ့ ကုထုံး သုံးခုထဲက တစ်ခုကို ရွေးနိုင်ဖို့
  • Thread တွေ join ပြီးမှ ရလဒ်တွေကို ဖတ်ပြီး run တိုင်း output တူတဲ့ program ရေးနိုင်ဖို့
  • std::stop_token နဲ့ request_stop() ကို သုံးပြီး worker loop ကို cooperative နည်းနဲ့ ရပ်နိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

Concurrency ကို ရိုးရိုးလေး ပြောရရင်

ယနေ့ computer အများစုမှာ core အများကြီး ပါပေမဲ့ ရိုးရိုး program တစ်ခုက တစ်ခုကိုပဲ သုံးပါတယ်။ Thread က program တစ်ခုတည်းထဲမှာ ပြိုင်တူ run နေတဲ့ နောက်ထပ် လုပ်ဆောင်ချက် လမ်းကြောင်းတစ်ခုပါ။ ဖိုင် တစ်ထောင်ကို ခွဲခြမ်းစိတ်ဖြာဖို့ အလုပ်ကို အပိုင်း လေးပိုင်း ခွဲပြီး thread လေးခုကို ပေးလိုက်ရင် core လေးခုလုံး တစ်ပြိုင်နက် အလုပ်လုပ်နိုင်ပါတယ်။

မီးဖိုချောင်တစ်ခုထဲက စားဖိုမှူး လေးယောက်လို စဉ်းစားကြည့်ပါ: တစ်ယောက်ချင်းစီ ကိုယ်ပိုင် ဓားပြားပေါ်မှာ လုပ်နေသရွေ့ အရာအားလုံး အဆင်ပြေပါတယ်။ ပြဿနာက နှစ်ယောက် တစ်ချိန်တည်း အိုးတစ်လုံးတည်းကို ဆားခတ်တဲ့အခါ စတာပါ။ Concurrency သင်ခန်းစာ အများစုက အဲဒီ မျှဝေထားတဲ့ အိုးကို ဘယ်လို ကာကွယ်မလဲ ဆိုတာပါပဲ။

Problem → Why → Solution

ပြဿနာ: run တိုင်း ကွဲပြားတဲ့ counter

Thread လေးခုက shared counter တစ်ခုကို တစ်ခုစီ 100000 ခါ တိုးပါတယ်၊ ဒါကြောင့် ရလဒ်က 400000 ဖြစ်သင့်ပါတယ်။ စက်တစ်လုံးပေါ်မှာ ငါးခါ run တော့ 236686၊ 162324၊ 146455၊ 159018 နဲ့ 169839 လို့ ကွဲပြားတဲ့ number ငါးခု ထွက်လာပြီး တစ်ခုမှ မှန်ကန်ခြင်း မရှိပါဘူး။ Thread တစ်ခုတည်းနဲ့ test လုပ်ရင်တော့ အမြဲ မှန်ပါတယ်။

racy_counter.cpp
#include <iostream>
#include <thread>
#include <vector>

int main() {
    int counter = 0;                             // shared, unprotected
    {
        std::vector<std::jthread> threads;
        for (int t = 0; t < 4; ++t) {
            threads.emplace_back([&counter] {
                for (int i = 0; i < 100000; ++i) ++counter;   // data race
            });
        }
    }
    std::cout << "counter: " << counter << '\n';  // expected 400000
}

Update တွေ ဘာကြောင့် ပျောက်သွားတာလဲ

++counter က လုပ်ဆောင်ချက် တစ်ခုတည်း မဟုတ်ပါဘူး: value ကို ဖတ်၊ တစ် ပေါင်း၊ ပြန်ရေး ဆိုတဲ့ အဆင့် သုံးဆင့်ပါ။ Thread နှစ်ခုက 41 ကို တစ်ပြိုင်နက် ဖတ်ပြီး နှစ်ခုလုံး 42 ကို ရေးရင် increment တစ်ခု ပျောက်သွားပါတယ်။ C++ မှာ ဒါကို data race လို့ ခေါ်ပါတယ်: synchronization မရှိဘဲ thread နှစ်ခုက memory နေရာတစ်ခုတည်းကို ထိပြီး အနည်းဆုံး တစ်ခုက ရေးတာပါ။ ရလဒ်က undefined behaviour ဖြစ်လို့ number မှားတာကပဲ အကောင်းဆုံး အခြေအနေပါ။

Core concept: thread lifetime နဲ့ shared data ကို ကာကွယ်ခြင်း

Process တစ်ခုထဲက thread အားလုံးက memory တစ်ခုတည်းကို မျှသုံးပါတယ်: global variable တွေ၊ heap နဲ့ reference နဲ့ capture လုပ်ထားသမျှ။ အဲဒီ မျှဝေမှုက အားသာချက်လည်း ဖြစ်သလို အန္တရာယ်လည်း ဖြစ်ပါတယ်။ std::thread ကို ပျက်စီးမသွားခင် join() ဒါမှမဟုတ် detach() လုပ်ရပါမယ်၊ မဟုတ်ရင် destructor က std::terminate ကို ခေါ်ပြီး program ရုတ်တရက် ရပ်သွားပါတယ်။ C++20 ရဲ့ std::jthread (<thread> ထဲမှာ) က destructor မှာ stop ကို အရင် တောင်းပြီး join လုပ်ပါတယ်၊ ဒါကြောင့် { std::vector<std::jthread> ... } scope တစ်ခုက 'အားလုံးကို စောင့်' ဆိုတဲ့ သဘာဝကျတဲ့ အမှတ်ဖြစ်လာပါတယ်။

Data race ကို ကုထုံး သုံးမျိုးနဲ့ ကာကွယ်ပါတယ်။ အကောင်းဆုံးက လုံးဝ မမျှဝေတာပါ: thread တစ်ခုစီက ကိုယ်ပိုင် slot ဒါမှမဟုတ် copy ပေါ်မှာ အလုပ်လုပ်ပြီး join ပြီးမှ ရလဒ်တွေကို ပေါင်းပါတယ်။ Counter ဒါမှမဟုတ် flag တစ်ခုလို value တစ်ခုတည်းအတွက် std::atomic ကို သုံးပါ၊ ++ က ခွဲလို့မရတဲ့ အဆင့်တစ်ခု ဖြစ်သွားပါတယ်။ vector တစ်ခုထဲ ထည့်တာလို အဆင့်များတဲ့ update အတွက် std::mutex နဲ့ std::lock_guard ကို သုံးပါ၊ lock_guard က constructor မှာ lock လုပ်ပြီး destructor မှာ unlock လုပ်ပါတယ်။

နည်းလမ်းသုံးသင့်တဲ့နေရာကုန်ကျစရိတ်
Thread တစ်ခုစီ ကိုယ်ပိုင် slotခွဲလုပ်ပြီး နောက်မှ ပေါင်းတဲ့ အလုပ်မရှိသလောက်
std::atomic<T>counter၊ flag လို value တစ်ခုသေး
std::mutex + std::lock_guardအဆင့်များတဲ့ update၊ containerThread တွေ တန်းစီစောင့်ရ

std::stop_token က cooperative cancellation ပါ။ Callable ရဲ့ ပထမ parameter က std::stop_token ဖြစ်ရင် jthread က token တစ်ခု ပေးပို့ပါတယ်။ request_stop() က flag ကို set လုပ်ရုံပါ၊ thread က stop_requested() ကို ပုံမှန် စစ်ပြီး ကိုယ်တိုင် ထွက်ရပါတယ်။ Thread ကို အတင်း သတ်ပစ်တဲ့ standard နည်းလမ်း မရှိပါဘူး။

နောက်ဆုံးအချက်က output ပါ: thread အများကြီးကနေ std::cout ကို ရေးရင် << တစ်ခုချင်းစီက သီးခြား call ဖြစ်လို့ line တွေ ရောနှောသွားပါတယ်။ ရလဒ်တွေကို စုပြီး join ပြီးမှ main က print ထုတ်ပါ။ Line တစ်ကြောင်းချင်း မပြတ်ဖို့ပဲ လိုရင် C++20 std::osyncstream (<syncstream>) ကို သုံးနိုင်ပေမဲ့ line တွေရဲ့ အစီအစဉ်ကတော့ run တိုင်း ပြောင်းနိုင်ပါတယ်။

Thread တိုင်းကို ကိုယ်ပိုင် ဓားပြား ပေးပါ
  1. အလုပ်ကို ခွဲ: thread တစ်ခုကို အပိုင်းတစ်ခု
  2. Thread တစ်ခုစီ ကိုယ်ပိုင် slot မှာပဲ ရေး
  3. Shared value တွေကို atomic/mutex နဲ့
  4. Scope ပြီး = join၊ ပြီးမှ ရလဒ် ဖတ်

Join မတိုင်ခင် ဘယ်ရလဒ်ကိုမှ မဖတ်ပါနဲ့၊ jthread scope ရဲ့ closing brace က အဲဒီ နယ်နိမိတ်ပါ။

အထွေထွေ ပုံစံ

cpp
std::vector<Result> slots(workers);              // one slot per thread
{
    std::vector<std::jthread> threads;
    for (int w = 0; w < workers; ++w) {
        threads.emplace_back([&, w] { slots[w] = compute(w); });
    }
}                                                // all threads joined here

std::jthread worker([](std::stop_token token) {
    while (!token.stop_requested()) { /* one unit of work */ }
});
worker.request_stop();                           // ask; the thread decides when

Thread တိုင်းကို index ကို value နဲ့ ပေးပြီး ကိုယ်ပိုင် slot မှာပဲ ရေးခိုင်းပါ၊ block ပြီးတာနဲ့ jthread တွေ join ဖြစ်ပါတယ်။ ကြာရှည် run မယ့် worker က stop token ကို ယူပြီး loop တစ်ခါပတ်တိုင်း စစ်ပါတယ်။

Worked example: thread လေးခုနဲ့ ပေါင်းခြင်း

1 ကနေ 1000 အထိ number တွေကို thread လေးခုပေါ် ခွဲပေါင်းပါတယ်။ Thread တစ်ခုစီက partial vector ထဲက ကိုယ်ပိုင် slot ကိုပဲ ရေးလို့ lock မလိုပါဘူး၊ ပြီးဆုံးတဲ့ thread အရေအတွက်ကတော့ shared ဖြစ်လို့ std::atomic ကို သုံးထားပါတယ်။ Thread တွေ run တဲ့ အစီအစဉ်က run တိုင်း ကွာနိုင်ပေမဲ့ output ကတော့ အမြဲ တူပါတယ်၊ main က join ပြီးမှ print ထုတ်လို့ပါ။

parallel_sum.cpp
#include <atomic>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

int main() {
    std::vector<int> data(1000);
    std::iota(data.begin(), data.end(), 1);          // 1, 2, ..., 1000

    const int workers = 4;
    const std::size_t chunk = data.size() / workers;
    std::vector<long long> partial(workers, 0);      // one slot per thread
    std::atomic<int> finished{0};

    {
        std::vector<std::jthread> threads;
        for (int w = 0; w < workers; ++w) {
            threads.emplace_back([&, w] {            // copy w, share the rest
                auto first = data.begin() + w * chunk;
                auto last = (w == workers - 1) ? data.end() : first + chunk;
                partial[w] = std::accumulate(first, last, 0LL);
                ++finished;                          // atomic: safe from any thread
            });
        }
    }   // each jthread joins here, so all partial sums are written

    for (int w = 0; w < workers; ++w) {
        std::cout << "worker " << w << ": " << partial[w] << '\n';
    }
    long long total = std::accumulate(partial.begin(), partial.end(), 0LL);
    std::cout << "finished: " << finished << '\n';
    std::cout << "total: " << total << '\n';
}

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. One slot per threadstd::vector<long long> partial(workers, 0);

    Element လေးခုကို thread မစခင် ဖန်တီးထားလို့ thread တွေ run နေစဉ် vector ကိုယ်တိုင် ဘယ်တော့မှ မပြောင်းပါဘူး၊ element မတူတာတွေကို ရေးတာက data race မဟုတ်ပါဘူး။

  2. Capture w by valuethreads.emplace_back([&, w] {

    & က data၊ partial၊ finished တို့ကို reference နဲ့ မျှဝေပြီး w ကိုတော့ copy ကူးပါတယ်။ w ကို reference နဲ့ ယူရင် loop ဆက်ပတ်ရင်း ပြောင်းသွားမယ့် variable တစ်ခုတည်းကို thread အားလုံး မျှသုံးမိပါလိမ့်မယ်။

  3. Write only your own slotpartial[w] = std::accumulate(first, last, 0LL);

    Thread တစ်ခုစီက ကိုယ့် chunk ကို ပေါင်းပြီး partial[w] ကိုပဲ ရေးပါတယ်။ 0LL က ပေါင်းလဒ်ကို long long နဲ့ တွက်စေပါတယ်။

  4. An atomic shared counter++finished;

    finished က std::atomic<int> ဖြစ်လို့ thread လေးခုလုံး တစ်ပြိုင်နက် တိုးလည်း update တစ်ခုမှ မပျောက်ပါဘူး။ ရိုးရိုး int ဆိုရင် problem section ထဲက race ပြန်ဖြစ်ပါလိမ့်မယ်။

  5. The join point} // each jthread joins here, so all partial sums are written

    threads vector ပျက်တဲ့အခါ jthread တစ်ခုစီရဲ့ destructor က join လုပ်ပါတယ်။ ဒီ brace ပြီးမှ partial ကို ဖတ်တာက လုံခြုံပြီး မှန်ကန်ပါတယ်။

You should see
worker 0: 31375
worker 1: 93875
worker 2: 156375
worker 3: 218875
finished: 4
total: 500500
Thread တွေ ခွဲထွက်ပြီး ပြန်ဆုံပုံ
  1. main က data နဲ့ partial slot လေးခုကို ပြင်ဆင်
  2. jthread လေးခု စတင်၊ တစ်ခုစီ ကိုယ့် chunk ကို ပေါင်း
  3. Thread တွေ ပြိုင်တူ run ပြီး ကိုယ်ပိုင် slot မှာ ရေး
  4. Scope ပြီးတော့ jthread တိုင်း join
  5. main က partial တွေကို ဖတ်ပြီး print

Worker တစ်ခုကို ယဉ်ယဉ်ကျေးကျေး ရပ်ခိုင်းခြင်း

Background watcher တစ်ခုက stop တောင်းဆိုတဲ့အထိ ငါး millisecond တစ်ခါ စစ်ဆေးနေပါတယ်။ main က ခဏစောင့်ပြီး request_stop() ကို ခေါ်ကာ join လုပ်ပါတယ်။ Loop ဘယ်နှခါ ပတ်လဲဆိုတာက scheduler ပေါ် မူတည်လို့ program က အဲဒါကို print မထုတ်ဘဲ run တိုင်း တူညီတဲ့ အချက်တွေကိုပဲ ပြပါတယ်။

stop_token.cpp
#include <atomic>
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>

int main() {
    std::atomic<int> polls{0};
    std::atomic<bool> cleanedUp{false};

    std::jthread watcher([&](std::stop_token token) {
        while (!token.stop_requested()) {        // cooperative: the thread checks
            ++polls;
            std::this_thread::sleep_for(std::chrono::milliseconds(5));
        }
        cleanedUp = true;                        // runs after the loop exits
    });

    std::this_thread::sleep_for(std::chrono::milliseconds(30));
    watcher.request_stop();                      // ask, do not kill
    watcher.join();                              // wait until it has finished

    std::cout << std::boolalpha;
    std::cout << "stop requested: " << watcher.get_stop_token().stop_requested() << '\n';
    std::cout << "cleaned up: " << cleanedUp << '\n';
    std::cout << "joinable after join: " << watcher.joinable() << '\n';
}

Output က stop requested: true၊ cleaned up: true နဲ့ joinable after join: false ပါ။ Loop ပြီးမှ cleanedUp ကို set လုပ်တာက thread က ကိုယ်တိုင် cleanup လုပ်ခွင့်ရကြောင်း ပြပါတယ် — file ပိတ်တာ၊ ပြီးခဲ့တဲ့ အလုပ်ကို သိမ်းတာ စတာတွေပါ။ join() ကို ကိုယ်တိုင် ခေါ်ထားလို့ destructor က ထပ် join မလုပ်ပါဘူး။

Shared container အတွက် mutex

Thread လေးခုက shared counter ကို တိုးပြီး shared log vector ထဲကိုလည်း ထည့်ပါတယ်။ ++counter က တစ်ဆင့်တည်း ဖြစ်ပေမဲ့ push_back က size၊ capacity၊ element တွေကို ပြောင်းလို့ atomic က ကာကွယ်ပေးလို့ မရပါဘူး၊ mutex လိုပါတယ်။

mutex_log.cpp
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

int main() {
    std::vector<std::string> log;
    std::mutex logMutex;
    int counter = 0;                             // protected by logMutex too

    {
        std::vector<std::jthread> threads;
        for (int id = 0; id < 4; ++id) {
            threads.emplace_back([&, id] {
                for (int i = 0; i < 10000; ++i) {
                    std::lock_guard<std::mutex> lock(logMutex);   // unlocks at }
                    ++counter;
                }
                std::lock_guard<std::mutex> lock(logMutex);
                log.push_back("thread " + std::to_string(id) + " done");
            });
        }
    }

    std::cout << "counter: " << counter << '\n';
    std::cout << "log entries: " << log.size() << '\n';
}

ဒီ program က run တိုင်း counter: 40000 နဲ့ log entries: 4 ကို print ထုတ်ပါတယ်။ log ထဲက entry တွေရဲ့ အစီအစဉ်ကတော့ ပြောင်းနိုင်လို့ print မထုတ်ထားပါဘူး။ Mutex တစ်ခုက အဲဒါ ကာကွယ်တဲ့ data နဲ့ အမြဲ တွဲနေသင့်ပြီး lock ကို လိုအပ်တဲ့ အချိန် အတိုဆုံးပဲ ကိုင်ထားပါ။

လက်တွေ့ project တွေမှာ

လက်တွေ့ project တွေမှာ thread

Thread တွေကို အောက်ပါ နေရာတွေမှာ နေ့စဉ် တွေ့ရပါတယ်။ အများစုမှာ အခုလို pattern အခြေခံ သုံးခု — ခွဲလုပ်ပြီး ပေါင်း၊ shared state ကို ကာကွယ်၊ ယဉ်ယဉ်ကျေးကျေး ရပ် — ကို ပြန်သုံးပါတယ်:

  • Desktop နဲ့ mobile app တွေ: UI thread က responsive ဖြစ်နေအောင် file import၊ image processing လို လေးလံတဲ့ အလုပ်တွေကို background thread မှာ လုပ်ပြီး window ပိတ်တဲ့အခါ stop token နဲ့ ရပ်ပါတယ်။
  • Server တွေ: thread pool တစ်ခုက request တွေကို ပြိုင်တူ ကိုင်တွယ်ပြီး cache ဒါမှမဟုတ် statistics လို shared data ကို mutex ဒါမှမဟုတ် atomic နဲ့ ကာကွယ်ပါတယ်။
  • Data processing: log file တွေ၊ ပုံတွေ၊ simulation တွေကို chunk တွေခွဲပြီး thread တစ်ခုစီက ကိုယ်ပိုင် ရလဒ်ကို တွက်ကာ နောက်ဆုံးမှ ပေါင်းပါတယ် — ဒီ lesson ရဲ့ example အတိုင်းပါ။
  • Game engine တွေ: audio၊ physics နဲ့ asset loading တွေကို သီးခြား thread တွေမှာ run ပြီး frame တိုင်း သတ်မှတ်ထားတဲ့ sync point မှာ data ဖလှယ်ပါတယ်။

အမှားများ

Thread တွေနဲ့ ဖြစ်လေ့ရှိတဲ့ အမှားများ

std::thread ကို join မလုပ်ခြင်း

std::thread worker(task); ကို join ဒါမှမဟုတ် detach မလုပ်ဘဲ scope ပြီးသွားရင် destructor က std::terminate ကို ခေါ်ပါတယ်။ ဒီ lesson ရဲ့ toolchain မှာ program က message မပြဘဲ crash ဖြစ်သွားပြီး တခြား platform တွေမှာ ပြတဲ့ စာသား ကွဲပြားပါတယ်။ Destructor က join လုပ်ပေးတဲ့ std::jthread ကို သုံးပါ။

Loop variable ကို reference နဲ့ capture လုပ်ခြင်း

[&] { slots[w] = ...; } လို ရေးရင် thread အားလုံးက loop ဆက်တိုးနေတဲ့ w တစ်ခုတည်းကို မျှသုံးပြီး loop ပြီးတဲ့အခါ w ကိုယ်တိုင် ပျက်သွားပါတယ်။ Thread တွေ slot မှားရေးတာ ဒါမှမဟုတ် undefined behaviour ဖြစ်တာ ကြုံရပါမယ်။ [&, w] နဲ့ index ကို copy ကူးပါ။

Join မတိုင်ခင် ရလဒ်ကို ဖတ်ခြင်း

partial ကို jthread scope ထဲမှာပဲ print ထုတ်ရင် thread တွေ ရေးနေတုန်း ဖတ်မိတဲ့အတွက် ကိုယ်တိုင်က data race ဖြစ်ပါတယ်၊ တစ်ခါတလေ 0 တွေ မြင်ရပါမယ်။ ဖတ်တာကို scope ရဲ့ closing brace နောက်ကို ရွှေ့ပါ။

Thread တိုင်းကနေ std::cout ကို တိုက်ရိုက် ရေးခြင်း

Thread တွေက std::cout << "worker " << w << ... လို ရေးရင် << တစ်ခုချင်းစီ ကြားမှာ တခြား thread တွေ ဝင်ရေးလို့ line တွေ ရောနှောပြီး run တိုင်း output ကွဲပါတယ်။ ရလဒ်တွေကို slot ထဲ စုပြီး main ကနေ print ထုတ်ပါ။

Mini challenge

Mini challenge: thread လေးခုနဲ့ prime ရေတွက်ခြင်း

1 ကနေ 20000 အထိ prime number တွေကို range လေးခု ခွဲပြီး std::jthread လေးခုနဲ့ ရေတွက်ပါ။ Thread တစ်ခုစီက သူ့ range ရဲ့ prime အရေအတွက်ကို ကိုယ်ပိုင် slot မှာ ရေးပြီး စစ်ဆေးခဲ့တဲ့ number အရေအတွက် စုစုပေါင်းကို shared atomic counter မှာ ပေါင်းပါ။ Thread တွေ join ပြီးမှ range တစ်ခုချင်းရဲ့ ရလဒ်နဲ့ စုစုပေါင်းကို print ထုတ်ပါ။

  • isPrime(int) ကို ရိုးရိုး trial division နဲ့ ရေးရမယ်
  • std::vector<int> primesPerPart(4) ထဲမှာ thread တစ်ခုစီ ကိုယ့် index ကိုပဲ ရေးရမယ်
  • စစ်ခဲ့တဲ့ number အရေအတွက်ကို std::atomic<int> နဲ့ ပေါင်းရမယ်
  • Thread ထဲကနေ ဘာမှ print မထုတ်ရ၊ output က run တိုင်း တူရမယ်
parallel_primes.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

bool isPrime(int n) {
    // TODO: false below 2; otherwise try divisors d while d * d <= n
    return false;
}

int main() {
    const int limit = 20000;
    const int parts = 4;

    // TODO: a slot vector for the per-range counts and an atomic "checked" counter

    {
        // TODO: start one std::jthread per range; capture the range index by value
        // TODO: each thread counts primes in its range and writes only its slot
    }   // TODO: make sure nothing is read before this brace

    // TODO: print each range's count, then "checked N numbers, M primes"
}

ရလဒ်: numbers 1-5000: 669 primes၊ 5001-10000: 560၊ 10001-15000: 525၊ 15001-20000: 508 ပြီးရင် checked 20000 numbers, 2262 primes ကို ဘယ်နှခါ run run တူညီစွာ print ထုတ်ပါတယ်။

အရိပ်အမြွက် ကြည့်ရန်

Range p ဆိုရင် p * step + 1 ကနေ (p + 1) * step အထိပါ၊ step = limit / parts။ Lambda ကို [&, p] နဲ့ ရေးပြီး ရလဒ်ကို local variable ထဲမှာ အရင် ရေတွက်ကာ နောက်ဆုံးမှ slot ကို တစ်ခါတည်း ရေးပါ။

အဖြေ ကြည့်ရန်
parallel_primes.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

bool isPrime(int n) {
    if (n < 2) return false;
    for (int d = 2; d * d <= n; ++d) {
        if (n % d == 0) return false;
    }
    return true;
}

int main() {
    const int limit = 20000;
    const int parts = 4;
    const int step = limit / parts;              // 5000 numbers per thread

    std::vector<int> primesPerPart(parts, 0);    // each thread owns one slot
    std::atomic<int> checked{0};                 // shared counter, atomic

    {
        std::vector<std::jthread> threads;
        for (int p = 0; p < parts; ++p) {
            threads.emplace_back([&, p] {
                int from = p * step + 1;
                int to = (p + 1) * step;
                int found = 0;
                for (int n = from; n <= to; ++n) {
                    if (isPrime(n)) ++found;
                }
                primesPerPart[p] = found;        // write only our own slot
                checked += to - from + 1;
            });
        }
    }   // all four threads have joined here

    int total = 0;
    for (int p = 0; p < parts; ++p) {
        std::cout << "numbers " << p * step + 1 << "-" << (p + 1) * step
                  << ": " << primesPerPart[p] << " primes\n";
        total += primesPerPart[p];
    }
    std::cout << "checked " << checked << " numbers, " << total << " primes\n";
}

Quick Quiz 1 / 3

main ထဲမှာ std::thread t(work); ကို join ဒါမှမဟုတ် detach မလုပ်ဘဲ main ပြီးသွားရင် ဘာဖြစ်မလဲ?

Quick Quiz 2 / 3

Thread လေးခုက reference နဲ့ မျှသုံးထားတဲ့ ရိုးရိုး int counter ကို တစ်ခုစီ ++counter 100000 ခါ လုပ်ပါတယ်။ Program က ဘာ print ထုတ်နိုင်လဲ?

Quick Quiz 3 / 3

ဘယ် lambda ကို ပေးရင် std::jthread က stop token တစ်ခု ပေးပို့မလဲ?

မှတ်ထားရမယ့် အချက်များ

  • std::jthread က destructor မှာ stop တောင်းပြီး join လုပ်လို့ scope ရဲ့ closing brace က 'အားလုံးကို စောင့်' ဆိုတဲ့ အမှတ် ဖြစ်ပါတယ်။
  • Synchronization မရှိဘဲ memory တစ်နေရာကို thread နှစ်ခုက ထိပြီး တစ်ခုက ရေးရင် data race ဖြစ်ပြီး undefined behaviour ပါ။
  • အကောင်းဆုံးက မမျှဝေတာပါ (thread တစ်ခုကို slot တစ်ခု)၊ value တစ်ခုအတွက် std::atomic၊ အဆင့်များတဲ့ update အတွက် std::mutex။
  • std::stop_token က cooperative ပါ: request_stop() က တောင်းဆိုရုံ၊ thread က stop_requested() ကို စစ်ပြီး ကိုယ်တိုင် ထွက်ပါတယ်။
  • Thread တွေ join ပြီးမှ main ကနေ print ထုတ်ရင် output က run တိုင်း တူပါတယ်။

C++ Multithreading Reference — cppreference

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Concurrency with std::jthread | Thuta Learning