c++ - 在网站上:godbolt.org,只有在那里:如何使用 std::thread?

标签 c++ pthreads

这是我的代码:

#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/

相关文章:

c++ - 无法在 pthread 中从类型 void* (类名)(void*) 转换为类型 void* (*)(void*)

c - C 中的竞争条件

c++ - 如何在LLVM中删除无条件分支?

c++ - 不使用 WMI 访问主板信息

C++ boost,等待来自不同线程的var init

c - 多线程程序中线程的执行顺序

c++ - 用于 std::array 的前向列表初始化的可变参数模板

c++ - 正确声明模板参数 - 显式特化函数定义时的参数

c - C 中的逻辑问题。定义 pthread 上的交互数量

c - 无法理解 pthread_join()