c_cpp 线程初始化示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 线程初始化示例相关的知识,希望对你有一定的参考价值。

/*
	Threads initialization 
*/

#include <iostream>

// Functions and classes for managing threads are included in <thread>
#include <thread>

// The "initial function" of the thread
void hello()
{
	std::cout << "Hello Concurrent World 1!\n";
}

// The "callable" type object
class background_task
{
public:
	void operator()()
	{
		std::cout << "Hello Concurrent World 2!\n";
	}
};

int main()
{
	std::thread t1(hello);

	// This is an example of "C++ most vexing parse", which interprets this as function declaration taking function pointer as argument
	// std::thread t2(background_task());

	// This is better declared using uniform initialization syntax. The object is copied into the thread so beware of dangling pointers.
	std::thread t2{ background_task() };

	// Thread can also be initialized using lambda expression
	std::thread t3([]()
	{
		std::cout << "Hello Concurrent World 3!\n";
	});

	// Wait for the additional threads to finish. Calling "join" on a thread object detaches the object from the thread, losing all information about that thread.
	// Failing to call "join" or "detach" will destroy the thread in the std::thread object destructor. "Detach" detaches the thread from the thread object.
	t1.join();
	t2.join();
	t3.join();
}

以上是关于c_cpp 线程初始化示例的主要内容,如果未能解决你的问题,请参考以下文章

Linux 内核线程调度示例一 ④ ( pthread_attr_init 初始化线程属性对象 | 完整代码示例 )

Linux 内核线程调度示例一 ④ ( pthread_attr_init 初始化线程属性对象 | 完整代码示例 )

c_cpp 多线程

c_cpp 多线程

c_cpp 在后台运行线程

c_cpp QT - 线程睡眠