C++ 11多线程

C++11开始支持多线程了,之前的多线程编程都需要系统支持,在不同的系统下要用不同的API,使用起来比较复杂,
C++11提供了新头文件<thread> <mutex> <atomic> <future>等支持多线程

简单的C++11多线程例子

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

using namespace std;

void f(string name)
{
	cout << "hello " << name <<  endl;
}

int main()
{
	thread t(f, "maHuaTeng");	//第一个参数是线程函数,第二个参数是个可变参数,用于传递线程函数参数
	t.join();	//join()方法阻塞父线程,直到t线程结束为止
	cout << "main" << endl;
	system("pause");
	return 0;
}
C++11支持Lambda表达式,因此一个新线程的回调函数也可以是有一个Lambda表达式的形式,但是注意如果使用Lambda表达式最好不要使用引用的方式,应该使用值传递的方式来访问数据,
在多线程中使用引用容易造成混乱。下面的例子稍显复杂一下,用数组创建多个子线程,并用get_id()方法来获取当前线程的id
#include <thread>
#include <vector>
#include <string>
#include <iostream>
#include <mutex>

using namespace std;

int main()
{
	vector<thread> vec;
	mutex m;
	for(int i = 0; i < 5; i++)
	{
		/*thread t([](string name){
			cout << "hello" << name << "Thread id" << this_thread::get_id() << endl;
		}, "wangDong");*/
		vec.push_back(t);		
		线程对象不能被复制,所以将t添加到vec中会出现编译错误,只能用下面的方式添加到vec中
		vec.push_back(thread([&m](string name){		//[]中用来放置互斥锁等,如果没有可以空着,试着把&m去掉跟m.lock(), m.unlock()注释掉,屏幕输出不会跟预期的一样
			m.lock();
			cout << "hello" << name << "Thread id " << this_thread::get_id() << endl;
			m.unlock();
		}, "wangDong"));
	}
	for(auto & a:vec)	//auto:用来声明自动变量,a的类型与给a初值类型相同,auto类型变量必须被赋初值以明确变量类型
	{
		a.join();
	}
	cout << "main Thread/t" << this_thread::get_id() << endl;
	system("pause");
	return 0;
}

可以通过sleep_for让进程睡眠一段时间

#include <thread>
#include <mutex>
#include <iostream>

using namespace std;

int main()
{
	mutex m;
	thread t1([&](){
		this_thread::sleep_for(chrono::seconds(10));
		m.lock();
		for(int i = 0; i < 10; i++)
			cout << "thread t1" << endl;
		m.unlock();
	});
	thread t2([&](){
		this_thread::sleep_for(chrono::seconds(1));
		m.lock();
		for(int i = 0; i < 10; i++)
			cout << "thread t2" << endl;
		m.unlock();
	});
	t1.join();
	t2.join();
	cout << "main thread" << endl;
	system("pause");
	return 0;
}

由于t1睡眠时间较长,所以t2先执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值