【问题标题】:how to use argument inside of thread? (C++)如何在线程内使用参数? (C++)
【发布时间】:2018-05-03 09:16:17
【问题描述】:

我不能在线程 t 中使用延迟参数

void HelloWorldDelay(int Delay)

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

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

如何在线程 t 内部使用它?

睡眠(延迟)

【问题讨论】:

标签: c++ arguments


【解决方案1】:
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 ";
}

将进行捕获

【讨论】:

  • 这不是通过引用捕获Delay,线程启动时可能超出范围或线程中使用Delay?
  • @RichardCritten 它无法超出范围,因为 t.join() 将等待线程退出
  • @kimjaehui 会很友好,如果你能接受答案,那么
【解决方案2】:

我认为你应该这样调用:

#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;
}

【讨论】:

    猜你喜欢
    • 2011-03-30
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 2019-03-24
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多