从if语句中初始化C++11线程
Initializing C++11 threads from within an if statement
我在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()
语句的主体是一个块作用域,因此在其中创建的所有变量都绑定到其作用域。这意味着thread1
在if()
语句之外是不可访问的。
相反,您可以默认构造线程,然后将其分配给一个新线程:
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);
相关文章:
- C++ 11 线程在分离后会自动销毁吗?
- 在 C++11 线程中,std::mutex 对内存可见性有什么保证?
- 从从可调用参数创建的线程对象参数移动构造 C++11 线程
- C++11 线程段错误
- C++11 线程不以 SDL 结尾
- 如何调试此C 11线程代码
- C 11线程汇编错误传递字符串作为复制的引用
- 如何等待多个线程完成(使用 c++11 线程)
- 将元素从C 11线程安全地添加到向量中
- C++11 线程池示例与错误
- 为什么添加函数在C 11线程中无效
- Eclipse c++11 线程支持不起作用
- 如何定期唤醒 C++ 11 线程
- C 11线程不起作用
- C++11线程实现后端
- c++11 线程类如何使用类成员函数
- C++11 线程:在构造函数中启动并在析构函数中加入
- C++ 11 线程简单示例
- c++11线程、SFML和代码::块
- C++11线程提升容器