gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:50 26 4
gpt4 key购买 nike

我在 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() 语句的主体是 block 作用域,因此在其中创建的任何变量的生命都绑定(bind)到它的作用域。这意味着 thread1if() 语句之外不可访问。

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

std::thread thread1;

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

关于c++ - 从 if 语句中初始化 C++11 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com