jthread icon indicating copy to clipboard operation
jthread copied to clipboard

[Q] jthread with shared stop_source

Open perrog opened this issue 2 years ago • 0 comments

Is there any particular reason why jthread does not allow constructing with external stop_source? Was this ever considered in the standards? Can't see any problems with such constructor, so just curious why it isn't in the library. Well, the only ambiguity case I can find is whatever to do if the stop_source is already stopped.

int main()
{
  std::stop_source s;
  std::jthread p1{s, [](std::stop_token t){ // (does not work)
    doWork1(t);                             // t = s.get_token()
  }};

  std::jthread p2{s, [](std::stop_token t){  // (does not work)
    doWork2(t);                              // t = s.get_token()
  }};

  s.request_stop(); // stop both threads.
}

Obviously, this is trivial example, but more realistic scenarios can be a thread group, or dependent threads, that may benefit a shared stop_source.

perrog avatar Jul 12 '22 17:07 perrog