How to detach a thread in C++

1 Answer

0 votes
#include <iostream>
#include <thread>

using std::cout;
using std::endl;

void threadFunction()
{
	cout << "Start threadFunction()" << endl;

	std::this_thread::sleep_for(std::chrono::seconds(3));
	
	cout << "End threadFunction()" << endl;
}

void threadControl()
{
	cout << "Start threadControl()" << endl;

	std::thread t(threadFunction);
	t.detach();
	std::this_thread::sleep_for(std::chrono::seconds(1));

	cout << "End threadControl()" << endl;
}

int main()
{
	threadControl();

	cout << "main()" << endl;

	std::this_thread::sleep_for(std::chrono::seconds(4));

	cout << "End main()" << endl;

	return 0;
}

/*
run:

Start threadControl()
Start threadFunction()
End threadControl()
main()
End threadFunction()
End main()

*/

 



answered Feb 6, 2018 by avibootz

Related questions

1 answer 129 views
129 views asked Sep 1, 2024 by avibootz
2 answers 256 views
256 views asked Feb 7, 2018 by avibootz
1 answer 178 views
178 views asked Feb 6, 2018 by avibootz
1 answer 211 views
211 views asked Feb 6, 2018 by avibootz
1 answer 183 views
1 answer 197 views
1 answer 256 views
...