1.

Can The Ownership Of C++11 Threads Be Transferred At Runtime?

Answer»

YES. std::thread object owns a resource, where the resource is a current thread of EXECUTION. You can call std::move to move the ownership of the underlying resource from one std::thread object to another. The question is – why would you want to do that? Here's a scenario:You want to WRITE a function that CREATES a thread but does not want to wait for it to finish. Instead it wants to pass the thread to another function which will wait for the thread to finish and execute some action once the execution is done.

#include "stdafx.h"

#include <string>

#include <thread>

#include <iostream>

#include <functional>

using namespace std;

void FireHTTPGet()

{

std::this_thread::sleep_for(std::chrono::milliseconds(5000));

cout << "Finished Executing HTTP Get"<< endl;

}

void ProcessHTTPResult(thread t1)

{

t1.join();

cout << "HTTP Get Thread Finished Executing - Processing Result Data!" << endl;

}

int main()

{

thread t11(FireHTTPGet);

thread t12(ProcessHTTPResult, std::move(t11));

//Do bunch of other processing without waiting for t11 to finish - instead now we've shouldered off the 

// responsibility of monitoring t11 thread to t12.

//Finally wait for t12 to finish

t12.join();

return 0;

}

OUTPUT:

Finished Executing HTTP Get

HTTP Get Thread Finished Executing - Processing Result Data!

Yes. std::thread object owns a resource, where the resource is a current thread of execution. You can call std::move to move the ownership of the underlying resource from one std::thread object to another. The question is – why would you want to do that? Here's a scenario:You want to write a function that creates a thread but does not want to wait for it to finish. Instead it wants to pass the thread to another function which will wait for the thread to finish and execute some action once the execution is done.

#include "stdafx.h"

#include <string>

#include <thread>

#include <iostream>

#include <functional>

using namespace std;

void FireHTTPGet()

{

std::this_thread::sleep_for(std::chrono::milliseconds(5000));

cout << "Finished Executing HTTP Get"<< endl;

}

void ProcessHTTPResult(thread t1)

{

t1.join();

cout << "HTTP Get Thread Finished Executing - Processing Result Data!" << endl;

}

int main()

{

thread t11(FireHTTPGet);

thread t12(ProcessHTTPResult, std::move(t11));

//Do bunch of other processing without waiting for t11 to finish - instead now we've shouldered off the 

// responsibility of monitoring t11 thread to t12.

//Finally wait for t12 to finish

t12.join();

return 0;

}

OUTPUT:

Finished Executing HTTP Get

HTTP Get Thread Finished Executing - Processing Result Data!



Discussion

No Comment Found