0

i can't use delay argument inside of thread t

void HelloWorldDelay(int Delay)

{
    cout << "Hello World";
    atomic<bool> abort(false);
    thread t([&abort]() {
        Sleep(Delay);
        abort = true;
    });

    t.join();
    cout << Delay << "Ms ";
}

how to use it inside of thread t?

Sleep(Delay)

  • Why can't you use it in a thread? It's visible to your local thread variable. – Ron May 03 '18 at 09:18
  • 1
    Is the error you're getting about not capturing Delay in your lambda, by any chance? – tux3 May 03 '18 at 09:19
  • Yes you right, not capturing Delay error, can you help me? –  May 03 '18 at 09:21
  • 1
    well you captured abort do the same for delay – Tyker May 03 '18 at 09:22
  • Possible duplicate of [Error: variable "cannot be implicitly captured because no default capture mode has been specified"](https://stackoverflow.com/questions/30217956/error-variable-cannot-be-implicitly-captured-because-no-default-capture-mode-h) – tux3 May 03 '18 at 09:22
  • @kimjaehui See the question I linked above, this has already been answered in details before :) – tux3 May 03 '18 at 09:23
  • how to capture two value ? &abort and Delay –  May 03 '18 at 09:25
  • You put a comma between the two values. – tux3 May 03 '18 at 09:25

2 Answers2

0
void HelloWorldDelay(int Delay) {

  std::cout << "Hello World";
  std::atomic<bool> abort(false);
  std::thread t([&]() {
      std::this_thread::sleep_for(std::chrono::seconds(Delay));
      abort = true;
    });

  t.join();
  std::cout << Delay << "Ms ";
}

will do the capturing

Kaveh Vahedipour
  • 3,412
  • 1
  • 14
  • 22
0

I think you should invoke like this :

#include <iostream>
#include <fstream>
#include <thread>
#include <atomic>

using namespace std;

void HelloWorldDelay(int Delay)

{
    cout << "Hello World";
    atomic<bool> abort(false);
    thread t([&abort](int delay) {
        //sleep(Delay);
        std::this_thread::sleep_for(std::chrono::milliseconds(delay));

        abort = true;
    }, std::ref(Delay));

    t.join();
    cout << Delay << "Ms ";
}

int main()
{
    HelloWorldDelay(3);
    std::system("pause");
    return 0;
}
mystic_coder
  • 462
  • 2
  • 10