这是我的代码:
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
#include <iostream>
void f(int n)
{
for (int cnt = 0; cnt < n; ++cnt) {
std::this_thread::sleep_for(1s);
std::cout << "." << std::flush;
}
std::cout << std::endl;
}
int main()
{
std::thread t1 = std::thread(f, 5);
//t1.join();
t1 = std::thread(f, 5); // <- should abort if t1.join() is not done
t1.join();
}
对于网站,我使用 gcc9.2 执行器来查看未加入的线程被破坏时会发生什么,但这是编译器输出选项卡的内容:
Could not execute the program
Compiler returned: 1
Compiler stderr
/tmp/ccjlEO57.o: In function `std::thread::thread<void (&)(int), int&, void>(void (&)(int), int&)':
/opt/compiler-explorer/gcc-9.2.0/include/c++/9.2.0/thread:126: undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status
另外 - 当我将“-lpthread”添加到编译器选项...编辑框时,我收到一个不同的错误:
Program returned: 255
Program stderr
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
请注意,对于第二次运行,第一个
t1.join()
没有被注释掉(所以它应该运行良好)。这是否意味着您无法测试任何内容
std::thread
与其他令人难以置信的棒相关 Godbolt.org 网站?
最佳答案
在所有可能的情况下,godbolt.org 上的线程创建被故意禁用(以防止拒绝服务攻击或其他滥用),因此目前无法在该服务上使用 std::thread。
关于c++ - 在网站上:godbolt.org,只有在那里:如何使用 std::thread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58629747/