Reputation: 25
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?
Upvotes: 0
Views: 101
Reputation: 343
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:
using namespace std
is not recommended.
remember to join()
after you create a thread
return 0
for main()
printf()
is in stdio.h. use std::cout
for iostream
Upvotes: 1
Reputation: 6125
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;
}
Upvotes: 5