7

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?

CrashNeb
  • 394
  • 3
  • 12
  • 1
    You may need to explicitly add the threads library to your link inputs. – Gem Taylor Oct 30 '19 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 '19 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. – n. m. could be an AI Oct 30 '19 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 '19 at 16:31
  • I don't think it's documented anywere, I deduced it from the error message. – n. m. could be an AI Oct 30 '19 at 16:35
  • You could try [**coliru**](http://coliru.stacked-crooked.com/a/3cfbc9f8c46be41b) instead. It provides g++ 9.2 currently. – Scheff's Cat Oct 30 '19 at 16:51

2 Answers2

9

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

javs
  • 798
  • 10
  • 28
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.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243