【问题标题】:Initializing C++11 threads from within an if statement从 if 语句中初始化 C++11 线程
【发布时间】:2014-10-16 01:41:07
【问题描述】:

我在 C++11 中实现线程,每当我从 if 语句中启动线程时都会遇到编译问题。

我收到的错误是:

file.cpp: In function ‘int main(int, char**)’:
file.cpp:16:2: error: ‘thread1’ was not declared in this scope
  thread1.join();

当我将线程移到 if 语句之外时,一切都编译并运行良好。

我正在使用 g++ 版本 4.8.2 并使用 -std=c++11 编译器选项。

这段代码不会编译

#include <unistd.h>
#include <thread>
#include <iostream>

void testthread() {
    std::cout << "Thread was run" << std::endl;
}

int main(int argc, char**argv) {

    if (true) {
        std::thread thread1(testthread);
    }
    sleep(1);
    thread1.join();
    return 0;
}

此代码按预期编译和运行

#include <unistd.h>
#include <thread>
#include <iostream>

void testthread() {
    std::cout << "Thread was run" << std::endl;
}

int main(int argc, char**argv) {

    std::thread thread1(testthread);
    sleep(1);
    thread1.join();
    return 0;
}

【问题讨论】:

  • thread1 不存在于您的if 声明范围之外,此类问题必须有很多重复项。
  • 从非常清晰的错误消息中,问题应该立即显而易见......但也许你不知道范围是什么?

标签: c++ multithreading c++11 compiler-errors g++


【解决方案1】:

if() 语句的主体是块作用域,因此在其中创建的任何变量都绑定到其作用域。这意味着在if() 语句之外无法访问thread1

相反,您可以默认构造线程,然后将其分配给新线程:

std::thread thread1;

if (true) {
    thread1 = std::thread(testthread)
}

【讨论】:

    【解决方案2】:

    您在 if 块中声明线程变量。它只在那里可见。 如果确实需要在 if 块内部初始化并在外部使用,可以使用指针在 if 块内部分配。

    std::thread* pThread1 = nullptr;
    if (true) {
            pThread1 = new std::thread(testthread);
    }
    sleep(1);
    pThread1->join();
    delete(pThread1);
    

    【讨论】:

      猜你喜欢
      • 2019-05-30
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      相关资源
      最近更新 更多