alexthgreat _194
alexthgreat _194

Reputation: 25

How to make threads with functions: C++

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

Answers (2)

David Wu
David Wu

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:

  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

Upvotes: 1

Sid S
Sid S

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

Related Questions