c++11 多线程使用

创建线程

1.创建线程的方式:

  • 1.拷贝构造禁止了
  • 2.允许移动构造
  • 3.无参构造后我们可以对对象进行赋值操作
  • 4.传递可调用对象(例如包装器,泛函数,lambda,普通函数,静态成员函数) + 参数列表 进行创建
    在这里插入图片描述

2.样例展示

  1. lambda 创建方式
#include<iostream>
#include<thread>
#include<mutex>
#include <condition_variable>
#include<vector>
#include<atomic>
using namespace std;
int main()
{
	mutex mtx;
	int x = 0;
	int n = 10;
	int m;
	cin >> m;

	vector<thread> v(m);
	//v.resize(m);

	for (int i = 0; i < m; ++i)
	{
		// 移动赋值给vector中线程对象
		v[i] = thread([&](){
			for (int i = 0; i < n; ++i)
			{
				mtx.lock();

				cout << this_thread::get_id() << ":" << i << endl;
				std::this_thread::sleep_for(std::chrono::milliseconds(100));
				++x;

				mtx.unlock();
			}
		});
	}

	for (auto& t : v)
	{
		t.join();
	}

	cout << x << endl;

	return 0;
}

2.普通函数和function包装器 创建方式

#include <condition_variable>
#include<vector>
#include<atomic>
#include<functional>
using namespace std;

void Print(int n, int& x, mutex& mtx)
{
	for (int i = 0; i < n; ++i)
	{
		mtx.lock();

		cout <<this_thread::get_id()<<":"<<i << endl;
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		++x;

		mtx.unlock();
	}

}

class A
{
public:
	static void Print(int n, int& x,mutex& mtx)
	{
		for (int i = 0; i < n; ++i)
		{
			mtx.lock();

			cout << this_thread::get_id() << ":" << i << endl;
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
			++x;

			mtx.unlock();
		}

	}
};
int main()
{

	mutex m;
	int count = 0;
	function<void(int,int&,mutex&)> f1 = A::Print;
	thread t1(f1, 10, ref(count), ref(m));
	thread t2(f1, 10, ref(count), ref(m));
	//thread t1(&A::Print, 10, ref(count), ref(m));
	//thread t2(Print, 10, ref(count), ref(m));
	
	
	//&A::Print(10, ref(count), ref(m))//errer 因为地址是1 是错的
	t1.join();
	t2.join();
	cout << count << endl;

	return 0;
}

注意事项:
线程函数的传参都是拷贝,例如参数是引用类型,也是会拷贝传值的,原因是与底层实现有关(创建线程时参数首先传递给构造函数再传递给线程函数这个过程里出问题了) – 解决方案 “ref(引用对象)” 意思是强制以左值引用去传递

异常导致死锁

1.如何导致死锁


int main()
{
	mutex mtx;
	atomic<int> x = 0;
	//int x = 0;
	int n = 100;
	int m;
	cin >> m;

	vector<thread> v(m);
	for (int i = 0; i < m; ++i)
	{
		// 移动赋值给vector中线程对象
		v[i] = thread([&](){
			for (int i = 0; i < n; ++i)
			{
				mtx.lock();

				// 如果存在抛异常就死锁了,解决办法:我们使用try catch进行捕获
				try {
					cout << this_thread::get_id() << ":" << i << endl;
					std::this_thread::sleep_for(std::chrono::milliseconds(100));
				}
				catch (...)
				{
					mtx.unlock();
					throw;
				}

				mtx.unlock();

		
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
			}
		});
	}

	for (auto& t : v)
	{
		t.join();
	}

	cout << x << endl;

	return 0;
}

2.智能锁
智能锁像智能指针一样RALL机制,管理的资源声明周期随对象释放资源
不过c++库已经给我们实现了Lock guard类
Lock guard类通过RAII的方式对互斥锁进行了封装,在构造函数中进行加锁,在析构函数中自动解锁
如下模拟实现Lock guard类:

// RAII
template<class Lock>
class LockGuard
{
public:
	LockGuard(Lock& lk)
		:_lock(lk)
	{
		_lock.lock();
		cout << "thread:" << this_thread::get_id() << "加锁" << endl;
	}

	~LockGuard()
	{
		cout << "thread:" << this_thread::get_id() << "解锁" << endl << endl;
		_lock.unlock();
	}
private:
	Lock& _lock;
};
int main()
{
	mutex mtx;
	atomic<int> x = 0;
	//int x = 0;
	int n = 100;
	int m;
	cin >> m;

	vector<thread> v(m);
	for (int i = 0; i < m; ++i)
	{
		// 移动赋值给vector中线程对象
		v[i] = thread([&](){
			for (int i = 0; i < n; ++i)
			{
				{
					// 11:54继续
					lock_guard<mutex> lk(mtx);
					// 如果存在抛异常就死锁了
					cout << this_thread::get_id() << ":" << i << endl;
				}

				std::this_thread::sleep_for(std::chrono::milliseconds(100));
			}
		});
	}

	for (auto& t : v)
	{
		t.join();
	}

	cout << x << endl;

	return 0;
}

实现两个线程交互的打印奇数和偶数(面试题)

考察条件变量的使用,跟wait()与POSIX库用法差不多,都是需要循环检测条件是否满足

//方法一:不确定是否正确


// 实现两个线程交互的打印奇数和偶数
// 两个线程交错打印1-100,一个打印奇数,一个打印偶数
//int main()
//{
//	int i = 0;
//	int n = 100;
//
//	thread t1([&](){
//		while (i < n)
//		{
//			while (i % 2 != 0)
//			{
//				this_thread::yield();
//			}
//
//			cout <<this_thread::get_id()<<":"<<i << endl;
//			i += 1;
//		}
//	});
//
//
//	thread t2([&](){
//		while(i < n)
//		{
//			while (i % 2 == 0)
//			{
//				this_thread::yield();
//			}
//
//			cout << this_thread::get_id() << ":" << i << endl;
//			i += 1;
//		}
//	});
//
//	t1.join();
//	t2.join();
//
//	return 0;
//}

//方法二

int main()
{
	int i = 0;
	int n = 100;
	mutex mtx;
	condition_variable odd;//满足i为奇数
	condition_variable even;//满足i为偶数

	thread t1([&]() {

		while (i < n)
		{
			unique_lock<mutex> lock(mtx);
			//此时i为奇数才需要等待
			even.wait(lock, [&]()->bool{
				return i%2 == 0;
				});

			cout << this_thread::get_id() << ":偶数:" << i << endl;
			i++;
			odd.notify_one();
		}
		});

	thread t2([&]() {

		while (i < n)
		{
			unique_lock<mutex> lock(mtx);
			odd.wait(lock, [&]()->bool {
				return i % 2 != 0;
				});

			cout << this_thread::get_id() << ":奇数:" << i << endl;
			i++;
			even.notify_one();
		}
		});

	t1.join();
	t2.join();
	return 0;
}

//方法三

int main()
{
	int i = 0;
	int n = 100;
	mutex mtx;
	condition_variable cv;
	bool ready = true;

	// t1打印奇数
	thread t1([&](){
		while (i < n)
		{
			{
				unique_lock<mutex> lock(mtx);
				cv.wait(lock, [&ready](){return !ready; });

				cout << "t1--" << this_thread::get_id() << ":" << i << endl;
				i += 1;

				ready = true;

				cv.notify_one();
			}

			//this_thread::yield();
			this_thread::sleep_for(chrono::microseconds(100));
		}
	});

	// t2打印偶数
	thread t2([&]() {
		while (i < n)
		{
			unique_lock<mutex> lock(mtx);
			cv.wait(lock, [&ready](){return ready; });

			cout <<"t2--"<<this_thread::get_id() << ":" << i << endl;
			i += 1;
			ready = false;

			cv.notify_one();
		}
	});

	this_thread::sleep_for(chrono::seconds(3));

	cout << "t1:" << t1.get_id() << endl;
	cout << "t2:" << t2.get_id() << endl;

	t1.join();
	t2.join();

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2023框框

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值