[C++ Multithreading Series] [1] Using detch to implement daemon threads

1. When the main thread ends, even if the thread of detch is an infinite loop, it will still be terminated.

#include<iostream>
#include<thread>
using namespace std;

void f() 
{
	int i = 0;
	while (true)
	{
		cout << "i=" << i << endl;
		i++;
	}
}

int main(int argc, int * argv[])
{
	thread t(f);
	t.detach();

	cout << "main" << endl;
	//system("pause");
	return 0;
}

After the mian ends, the t thread will also end, and the daemon thread is not implemented.

2. Use detch to implement the daemon thread, the main thread cannot end.

#include<iostream>
#include<thread>
using namespace std;

void f() 
{
	int i = 0;
	while (true)
	{
		cout << "i=" << i << endl;
		i++;
	}
}

int main(int argc, int * argv[])
{
	thread t(f);
	t.detach();

	cout << "main" << endl;
	while (true) {

	}
	return 0;
}

The result is as follows:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325369521&siteId=291194637