0

I'm trying to make threads using C++'s standard library via functions.

#include <iostream> #include <thread> using namespace std; void print() { printf("PRINT\n"); printf("PRINT2\n"); } void createThread() { thread newThread(print); } int main() { createThread(); cin.get(); } 

the program compiles and runs but once the thread is finished it creates a "debug error". Any thoughts?

3
  • You're not supposed to use printf in a thread subroutine Commented Apr 22, 2019 at 3:23
  • What sort of "debug error"? Is there a message? Does the program misbehave? Commented Apr 22, 2019 at 3:38
  • 3
    @stackptr - says who? Commented Apr 22, 2019 at 3:50

2 Answers 2

5

The problem is that your thread object goes out of scope before you call its detach() or join() member.

Try this:

int main() { thread newThread(print); ... newThread.join(); return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

1

If your "debug error" means the compiler error message, you should check if -pthread flag is set. That is compile the code with

$ g++ -std=c++11 main.cpp -pthread -o main 

If your "debug error" means the runtime error, you should remember to join() after you create a thread.

source code:

#include <iostream> #include <thread> void print() { std::cout << "PRINT" << std::endl;; std::cout << "PRINT 2" << std::endl;; } void create_thread() { std::thread print_thread(print); print_thread.join(); // remember to join() } int main() { create_thread(); return 0; } 

In addition, you may pay attention to 4 additional points:

  1. using namespace std is not recommended.

  2. remember to join() after you create a thread

  3. return 0 for main()

  4. printf() is in stdio.h. use std::cout for iostream

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.