summaryrefslogtreecommitdiffstats
path: root/src/common/thread_worker.cpp
blob: 8f9bf447ae73635fb5ea76ca6e62c4e6448707a7 (plain) (blame)
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright 2020 yuzu emulator team
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.

#include "common/thread.h"
#include "common/thread_worker.h"

namespace Common {

ThreadWorker::ThreadWorker(std::size_t num_workers, const std::string& name) {
    for (std::size_t i = 0; i < num_workers; ++i)
        threads.emplace_back([this, thread_name{std::string{name}}] {
            Common::SetCurrentThreadName(thread_name.c_str());

            // Wait for first request
            {
                std::unique_lock lock{queue_mutex};
                condition.wait(lock, [this] { return stop || !requests.empty(); });
            }

            while (true) {
                std::function<void()> task;

                {
                    std::unique_lock lock{queue_mutex};
                    condition.wait(lock, [this] { return stop || !requests.empty(); });
                    if (stop || requests.empty()) {
                        return;
                    }
                    task = std::move(requests.front());
                    requests.pop();
                }

                task();
            }
        });
}

ThreadWorker::~ThreadWorker() {
    {
        std::unique_lock lock{queue_mutex};
        stop = true;
    }
    condition.notify_all();
    for (std::thread& thread : threads) {
        thread.join();
    }
}

void ThreadWorker::QueueWork(std::function<void()>&& work) {
    {
        std::unique_lock lock{queue_mutex};
        requests.emplace(work);
    }
    condition.notify_one();
}

} // namespace Common