【发布时间】:2019-10-30 16:19:39
【问题描述】:
这是我的代码:
#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”添加到 Compiler options... 编辑框时,我得到一个不同的错误:
Program returned: 255
Program stderr
terminate called after throwing an instance of 'std::system_error'
what(): Resource temporarily unavailable
请注意,对于第二次运行,第一个 t1.join() 没有被注释掉(所以它应该可以正常运行)。
这是否意味着您无法在非常棒的 godbolt.org 网站上测试与 std::thread 相关的任何内容?
【问题讨论】:
-
您可能需要将线程库显式添加到链接输入中。
-
我已经更新了我的问题 - 编译器选项不起作用。您能否将其取消标记为重复项。它与网站特别相关:Godbolt.org 以及如何让它在那里工作。
-
godbolt.org 已禁用创建线程。向所有者付费以启用它们、使用其他服务或拥有自己的计算机。
-
@n.m.如果我没有看到明显的东西,我很抱歉 - 但我没有注意到网站上任何解释这一点的东西。所以我希望在这里得到确认......你提供的。如果您添加答案,我会将其标记为此类。
-
我不认为它被记录在案,我是从错误消息中推断出来的。