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

Initializing C++11 threads from within an if statement

本文关键字:C++11 线程 初始化 if 语句      更新时间:2023-10-16

我在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;
}

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

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

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

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

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