Alexander  Shmuratko
Alexander Shmuratko

Reputation: 341

C++11 threads: How to start a thread and, separately, check for its completion?

In C++11 the call

my_thread.join();

runs the thread and waits for its completion. And I need to, first, run the thread and, later, to wait for its completion. The way it's done, say, in UNIX systems:

pthread_create(...)

runs a thread, and

pthread_join(...)

waits for completion. Is this possible with C++11?

Upvotes: 0

Views: 94

Answers (2)

qrikko
qrikko

Reputation: 2603

Well, C++11 threads are in fact (as far as I know) using the systems main threading facility so for a unix-system it will probably utilize posix threads.

A simple example of doing what I think you want to do could be something like:

#include <thread>
#include <iostream>

 // The function run from the thread i.e. "run the thread" part of your question.
 void things_to_do_in_thread() {
    std::cout << "Hello World" << std::endl;
}

int main() {
    // This create the thread and call the function
    std::thread my_thread(things_to_do_in_thread);

    //Join with the main thread
    my_thread.join();

    return 0;
}

You could also give a lambda-function to run which would look like this:

#include <thread>
#include <iostream>

int main() {
    std::thread my_thread([](){
        std::cout << "Hello world" << std::this_thread::get_id() << std::endl;
    });

    my_thread.join();
}

I hope that is what you are asking for and that it will help you familiarize with the std thread implementation in C++11.

Upvotes: 0

ikh
ikh

Reputation: 10427

std::thread::join() does not make thread run. When std::thread object constructs with function-object parameters, The thread runs.

For example:

std::thread thrd1(doSomething); // Thread starts
// Some codes...
thrd1.join(); // Wait for thread exit
std::thread thrd2; // default constructor
thrd2 = std::thread(doSomething);
// blablabla...
thrd2.join();

Upvotes: 2

Related Questions