0

I'm having trouble multithreading in C++. Here's my code:

#include <iostream>
#include <thread>

bool stop = false;

void loop() {
    while (!stop) {
        // Do something...
    }
}

int main() {
    std::thread t(loop);
    
    std::cin.get();
    stop = true;
    t.join();

    std::cout << "\nPress any key to continue";
    std::cin.get();

    return 0;
}

What I'm trying to accomplish is to break out of the loop in loop() as soon as a key is pressed. When I try to compile, it throws an error:

$ sudo g++ main.cpp 
/usr/bin/ld: /tmp/ccZOsb6T.o: in function `std::thread::thread<void (&)(), , void>(void (&)())':
main.cpp:(.text._ZNSt6threadC2IRFvvEJEvEEOT_DpOT0_[_ZNSt6threadC5IRFvvEJEvEEOT_DpOT0_]+0x20): undefined reference to `pthread_create'
collect2: error: ld returned 1 exit status

Am I doing something wrong? Thanks for any help.

Dudek
  • 54
  • 1
  • 7
  • 6
    Pthreads are lurking underneath `std::thread`. Add `-lpthread` to the build command. `g++ -lpthread main.cpp`. Side note: I've never needed sudo to run a compiler. – user4581301 May 03 '21 at 20:04
  • Linking fails because you're not providing the definition of `pthread_create`: https://stackoverflow.com/questions/17264984/undefined-reference-to-pthread-create – Martin May 03 '21 at 20:05
  • 5
    @user4581301 The usual way for `g++` is just to use the `-pthread` flag. – πάντα ῥεῖ May 03 '21 at 20:06
  • Thanks to everyone who commented; the error has been fixed using the `-pthread` flag. And @user4581301 , I also don't really know why, but for some reason I have to use sudo or it can't write the output file due to lack of permission. – Dudek May 03 '21 at 20:13
  • Odd. Check where the output files are going. Clearly at least one is going somewhere you're not allowed to write. Probably worth clearing the problem up to prevent /understand future problems. – user4581301 May 03 '21 at 20:15
  • Added the Issue with std::thread from c++11 duplicate because one of the answers directly addresses the `-lpthread`/`-pthread` thing. – user4581301 May 03 '21 at 20:16
  • Perhaps using a makefile and gnu make might help. Then you can add a line to the makefile like so: CXXFLAGS := -Wall -g -std=c++11 -pthread – mrflash818 May 03 '21 at 20:17

0 Answers0