【发布时间】: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++