Bencg

 avatar
unknown
c_cpp
2 years ago
1.9 kB
27
Indexable
#include <iostream>
#include <string>
#include <vector>
#include <condition_variable>
#include <chrono>
#include <thread>
#include <iomanip>

std::mutex mutex;
std::condition_variable cv;
bool sleep_cond = true;

void WaitOneByOne() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [](){ return !sleep_cond; });
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    lock.unlock();
    cv.notify_one();
}

void WakeOne() {
    std::unique_lock<std::mutex> lock(mutex);
    sleep_cond = false;
    lock.unlock();
    cv.notify_one();
}

void WaitAll() {
    std::unique_lock<std::mutex> lock(mutex);
    cv.wait(lock, [](){ return !sleep_cond; });
    std::this_thread::sleep_for(std::chrono::milliseconds(10));
}

void WakeAll() {
    std::unique_lock<std::mutex> lock(mutex);
    sleep_cond = false;
    lock.unlock();
    cv.notify_all();
}


int main()
{
    size_t threadCnt = 100;
    std::vector<std::jthread> t;
    t.reserve(threadCnt);
    { // wake one by one
        auto timeStart = std::chrono::system_clock::now();
        for (size_t i = 0; i < threadCnt; ++i) {
            t.emplace_back(WaitOneByOne);
        }
        sleep_cond = false;
        WakeOne();
        t.clear();
        auto timeEnd = std::chrono::system_clock::now();
        std::cout << "ONE BY ONE: " << std::setw(9) <<  std::chrono::duration<double>(timeEnd - timeStart).count() << " s\n";
    }

    std::cout << '\n';
    t.reserve(threadCnt);

    { // wake all
        auto timeStart = std::chrono::system_clock::now();
        for (size_t i = 0; i < threadCnt; ++i) {
            t.emplace_back(WaitAll);
        }
        sleep_cond = false;
        WakeAll();
        t.clear();
        auto timeEnd = std::chrono::system_clock::now();
        std::cout << "ALL: " << std::setw(9) <<  std::chrono::duration<double>(timeEnd - timeStart).count() << " s\n";
    }
}
Editor is loading...