8

Here is my code:

#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();
}

For the website, I am using a gcc9.2 executor to see what happens when an un-joined thread is destructed, but this is content of the compiler output tab:

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

Also - when I add "-lpthread" to the Compiler options... edit box, I get a different error:

Program returned: 255
Program stderr

terminate called after throwing an instance of 'std::system_error'
  what():  Resource temporarily unavailable

Please note that for this 2nd run, the first t1.join() was not commented out (so it should run fine).

Does this mean you can't test anything std::thread related on the otherwise incredibly awesome godbolt.org website?

6
  • 1
    You may need to explicitly add the threads library to your link inputs.
    – Gem Taylor
    Oct 30, 2019 at 16:22
  • I have already updated my question - the compiler option does not work. Could you please unmark this as a duplicate. It is specifically related to the website: Godbolt.org and how to make it work there.
    – CrashNeb
    Oct 30, 2019 at 16:26
  • 1
    godbolt.org has disabled creating threads. Pay the owner to enable them, use some other service, or get your own computer. Oct 30, 2019 at 16:29
  • @n.m. I am sorry if I didn't see something obvious - but I didn't notice anything on the site that explained this. So I was hoping for confirmation here... which you provided. If you add an answer I will mark it as such.
    – CrashNeb
    Oct 30, 2019 at 16:31
  • I don't think it's documented anywere, I deduced it from the error message. Oct 30, 2019 at 16:35

2 Answers 2

10

The site now supports threads. Add -pthread to the compiler arguments.

1
  • Pity that std::thread::hardware_concurrency() says only 2.
    – Yyttsa
    Feb 22, 2022 at 14:46
5

In all likelyhood, thread creation is disabled on godbolt.org on purpose (to prevent denial of service attacks or other abuse), so there is currently no way to use std::thread on that service.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.