Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use std::jthread for background threads #216

Open
Shillaker opened this issue Jan 12, 2022 · 1 comment
Open

Use std::jthread for background threads #216

Shillaker opened this issue Jan 12, 2022 · 1 comment

Comments

@Shillaker
Copy link
Collaborator

We can use std::jthread with a stop_token:

#include <thread>
#include <iostream>
 
using namespace std::literals::chrono_literals;
 
void f(std::stop_token stop_token, int value)
{
    while (!stop_token.stop_requested()) {
        std::cout << value++ << ' ' << std::flush;
        std::this_thread::sleep_for(200ms);
    }
    std::cout << std::endl;
}
 
int main()
{
    std::jthread thread(f, 5); // prints 5 6 7 8... for approximately 3 seconds
    std::this_thread::sleep_for(3s);
    // The destructor of jthread calls request_stop() and join().
}

from https://en.cppreference.com/w/cpp/thread/stop_token

@csegarragonz
Copy link
Collaborator

Partially done in #251

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants