Created
October 10, 2024 14:54
-
-
Save 27Cobalter/b424959c1c7dea8d8fa39db405b1d82b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
#include <cstdint> | |
#include <functional> | |
#include <iostream> | |
#include <memory> | |
#include <ranges> | |
#include <string_view> | |
#include <syncstream> | |
#include <thread> | |
void Func1(std::stop_token token, std::string_view arg) { | |
for (auto i : std::views::iota(0, 20)) { | |
if (!token.stop_requested()) { | |
std::osyncstream os(std::cout); | |
os << std::format("{}: {}", i, arg) << std::endl; | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
} | |
} | |
class Class1 { | |
private: | |
std::unique_ptr<std::jthread> th_; | |
std::string_view pref_; | |
public: | |
Class1(std::string_view pref) : pref_(pref){}; | |
template <int impl> | |
void Start(std::string_view str); | |
void Cancel(); | |
void Join(); | |
void Worker(std::stop_token token, std::string_view str); | |
}; | |
template <int impl> | |
void Class1::Start(std::string_view arg) { | |
if constexpr (impl == 0) { | |
th_ = std::make_unique<std::jthread>( | |
[this](std::stop_token token, std::string_view arg) { this->Worker(token, arg); }, arg); // これか | |
} else { | |
th_ = std::make_unique<std ::jthread>(std::bind_front(&Class1::Worker, this), arg); // これ | |
} | |
} | |
void Class1::Cancel() { | |
th_->request_stop(); | |
} | |
void Class1::Join() { | |
th_->join(); | |
} | |
void Class1::Worker(std::stop_token token, std::string_view arg) { | |
for (auto i : std::views::iota(0, 20)) { | |
if (!token.stop_requested()) { | |
std::osyncstream os(std::cout); | |
os << std::format("{}: {}, {}", i, pref_, arg) << std::endl; | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
} | |
} | |
auto main() -> int { | |
Class1 c0("c0"); | |
Class1 c1("c1"); | |
std::unique_ptr<std::jthread> th1 = std::make_unique<std::jthread>(Func1, "func"); | |
c0.Start<0>("lambda"); | |
c1.Start<1>("bind"); | |
std::this_thread::sleep_for(std::chrono::seconds(10)); | |
th1->request_stop(); | |
c0.Cancel(); | |
c1.Cancel(); | |
th1->join(); | |
c0.Join(); | |
c1.Join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment