std::thread 用法

描述:
       std::thread是c++11引入的线程库的一部分,它允许开发人员通过创建独立的执行线程来执行并发任务。使用std::thread,我们可以轻松地将任务分配给不同的线程,并在不同线程之间进行通信和同步。

创建线程:

#include <iostream>
#include <thread>
#include <string>

void MyThread(const std::string& str)
{
	std::cout << str << std::endl;
}

class CTest
{
public:
	void MyThread(const std::string& str)
	{
		std::cout << str << std::endl;
	}
};

int main()
{
	std::string str = "hello world";

	//lambda表达式
	std::thread t1([str]() {
		std::cout << str << std::endl;
	});
	if (t1.joinable())
		t1.join();

	//普通函数
	std::thread t2(MyThread,str);
	if (t2.joinable())
		t2.join();

	//成员函数
	CTest t;
	std::thread t3(&CTest::MyThread,&t,str);
	if (t3.joinable())
		t3.join();

	return 0;
}

线程id:

#include <iostream>
#include <thread>
#include <string>

int main()
{
	std::string str = "hello world";

	//lambda表达式
	std::thread t1([str]() {
		std::cout << str << std::endl;
	});

	std::thread::id idMain = std::this_thread::get_id();
	std::thread::id idT1 = t1.get_id();
	std::cout << "main id " << idMain << std::endl;
	std::cout << "t1 id " << idT1 << std::endl;

	if (t1.joinable())
		t1.join();

	return 0;
}

线程休眠:

//休眠1秒
std::chrono::milliseconds sleeptime(1000);
std::this_thread::sleep_for(sleeptime);

类中创建线程:

#include <iostream>
#include <thread>
#include <atomic>

class CTest
{
public:
	CTest()
	{
		m_bRunThread = true;
		m_thread = std::thread(&CTest::MyThread,this);
	}
	~CTest()
	{
		m_bRunThread = false;
		if (m_thread.joinable())
			m_thread.join();
	}

private:
	void MyThread()
	{
		while (m_bRunThread)
		{
			std::cout << "hello world" << std::endl;

			//休眠1秒
			std::chrono::milliseconds sleeptime(1000);
			std::this_thread::sleep_for(sleeptime);
		}
	}

private:
	std::thread			m_thread;
	std::atomic<bool>	m_bRunThread;
};

int main()
{
	CTest t;

	//休眠5秒
	std::chrono::milliseconds sleeptime(5000);
	std::this_thread::sleep_for(sleeptime);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值