从 if 语句中初始化 C++11 线程

jpr*_*e14 0 c++ multithreading compiler-errors g++ c++11

我在 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();
Run Code Online (Sandbox Code Playgroud)

当我将线程移到 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;
}
Run Code Online (Sandbox Code Playgroud)

此代码按预期编译并运行

#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;
}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 5

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

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

std::thread thread1;

if (true) {
    thread1 = std::thread(testthread)
}
Run Code Online (Sandbox Code Playgroud)