在网站:godbolt.org 上,并且仅在那里:如何使用 std::thread?

Cra*_*Neb 8 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();
}
Run Code Online (Sandbox Code Playgroud)

对于该网站,我使用 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
Run Code Online (Sandbox Code Playgroud)

另外 - 当我将“-lpthread”添加到编译器选项...编辑框时,我收到不同的错误:

Program returned: 255
Program stderr

terminate called after throwing an instance of 'std::system_error'
  what():  Resource temporarily unavailable
Run Code Online (Sandbox Code Playgroud)

注意,对于第二次运行,第一次t1.join()没有被注释掉(所以它应该运行良好)。

这是否意味着您无法std::thread在令人难以置信的godbolt.org网站上测试任何相关内容?

jav*_*avs 10

该网站现在支持线程。添加-pthread到编译器参数。


n. *_* m. 5

很可能,godbolt.org 上有意禁用线程创建(以防止拒绝服务攻击或其他滥用),因此目前无法在该服务上使用 std::thread。