C++多线程编程(第二章 多线程通信和同步)

1、多线程状态

1.1线程状态说明

初始化(Init):该线程正在被创建;
就绪(Ready):该线程在就绪列表中,等待CPU调度;
运行(Running):该线程正在运行;
阻塞(Blocked):该线程被阻塞挂起,Blocked状态包括:pend(锁、事件、信号量等阻塞)、suspend(主动pend)、delay(延时阻塞)、pendtime(因为锁、事件、信号量时间等超时等待)
退出(Exit):该线程运行结束,等待父线程回收其控制块资源;
在这里插入图片描述

2、竞争状态(Race Condition)和临界区(Critical Section)

2.1、竞争状态

多线程同时读写共享数据

2.2、临界区

读写共享数据代码片段

避免竞争状态策略,对临界区进行保护,同时只能有一个线程进入临界区

3、互斥体和锁mutex

3.1互斥锁mutex

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

using namespace std;
static mutex mux;//全局锁

void TestThread()
{
	//获取锁资源,如果没有锁则阻塞等待
	mux.lock();
	cout << "=======================================" << endl;
	cout << "test 001" << endl;
	cout << "test 002" << endl;
	cout << "test 003" << endl;
	cout << "=======================================" << endl;
	mux.unlock();
}

void TestThread2()
{//尝试获取锁
	//获取锁资源,如果没有锁则阻塞等待
	//mux.lock();
	for (;;)
	{
		if (!mux.try_lock())//有性能开销的,所以要等待一下
		{
			cout << "." << flush;
			this_thread::sleep_for(100ms);//等待一下再尝试

			continue;
		}
		cout << "=======================================" << endl;
		cout << "test 001" << endl;
		cout << "test 002" << endl;
		cout << "test 003" << endl;
		cout << "=======================================" << endl;
		mux.unlock();
		this_thread::sleep_for(3000ms);//等待一下,便于观察竞争的状态
	}
	
}
int main()
{
	printf("Demo1:\n");
	for (int i = 0; i < 2; i++)
	{
		thread th(TestThread);
		th.detach();
	}
	getchar();

	printf("Demo2:\n");
	for (int i = 0; i < 2; i++)
	{
		thread th(TestThread2);
		th.detach();
	}
	getchar();

	return 0;
}

3.2、互斥锁的坑_线程抢占不到资源的思考及解决方案

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

using namespace std;
static mutex mux;//全局锁

void ThreadMainMux(int i)
{
	for (;;)//死循环
	{
		mux.lock();
		cout << i << "[in]" << endl;
		this_thread::sleep_for(1000ms);//模拟干活
		mux.unlock();
		this_thread::sleep_for(1ms);//这是系统获取锁的关键,解锁后等待一下,其他线程好获取到锁,这样就可以并发的所有线程都可以在执行
	}
}


int main()
{
	//并发三个守护线程
	for (int i = 0; i < 3; i++)
	{
		thread th(ThreadMainMux,i);
		th.detach();
	}
	getchar();
	return 0;
}

解锁后没有等待的情况如下
在这里插入图片描述
解锁后等待1毫秒,让其他线程可以获取到锁,运行结果如下
在这里插入图片描述

3.3、超时锁应用 time_mutex(避免长时间死锁)

可以记录锁获取情况,多次超时,可以记录日志,获取错误情况

//超时锁应用 timed_mutex(避免长时间死锁)


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

using namespace std;
//static mutex mux;//全局锁
timed_mutex tmux;//超时锁
void ThreadMainTime(int i)
{
	for (;;)
	{
		//if (!tmux.try_lock_for(chrono::milliseconds(500)))//如果超时500毫秒,返回false
		if (!tmux.try_lock_for(500ms))//两种方式都可以
		{
			cout << i << "[try_lock_for timeout]" << endl;
			continue;
		}
		cout << i << "[in]" << endl;
		this_thread::sleep_for(2000ms);
		tmux.unlock();
		this_thread::sleep_for(1ms);
	}
}

int main()
{
	//并发三个守护线程
	for (int i = 0; i < 3; i++)
	{
		thread th(ThreadMainTime, i);
		th.detach();
	}
	getchar();
	return 0;
}

在这里插入图片描述

3.4、递归锁(可重入)recursive_mutex 和recursive_timed_mutex用于业务组合

同一个线程种同一把锁可以锁多次,避免了一些不必要的死锁;
组合业务,用到同一个锁

//可重入的锁,递归锁
#include <thread>
#include <iostream>
#include <string>
#include <mutex>

using namespace std;
//static mutex mux;//全局锁
//timed_mutex tmux;//超时锁

recursive_mutex rmux;//可重入的锁,

void Task1()
{//业务1
	rmux.lock();
	cout << "task1 [in]" << endl;
	rmux.unlock();
}
void Task2()
{//业务2
	rmux.lock();
	cout << "task2 [in]" << endl;
	rmux.unlock();
}

void ThreadMainRec(int i)
{
	for (;;)
	{
		rmux.lock();
		Task1();//这个任务中还用到了重入锁,普通锁是不能锁两次的,避免竞争
		cout << i << "[in]" << endl;
		this_thread::sleep_for(2000ms);
		Task2();//这个任务中还用到了重入锁,普通锁是不能锁两次的,避免竞争
		rmux.unlock();
		this_thread::sleep_for(1ms);

	}
}

int main()
{
	//并发三个守护线程
	for (int i = 0; i < 3; i++)
	{
		thread th(ThreadMainRec, i);
		th.detach();
	}
	getchar();
	return 0;
}

在这里插入图片描述

3.5、共享锁 shared_mutex

C++ 14共享超时互斥锁 shared_timed_mutex
C++ 17共享互斥锁 shareD_mutex
查看自己vs支持哪些C++版本,如下截图
在这里插入图片描述
共享锁中包含了共享锁和互斥锁,当互斥锁被锁定,所有共享锁都进不去;共享锁中的共享锁,只要在没有锁定共享锁中的互斥锁,共享锁中的共享锁都能进入;

//共享锁,读的时候所有线程都能读,写的时候读的线程不能读,只能写

#include <thread>
#include <iostream>
#include <string>
#include <mutex>
#include <shared_mutex>

using namespace std;
//static mutex mux;//全局锁
//timed_mutex tmux;//超时锁
//recursive_mutex rmux;//可重入的锁,

//shared_mutex smux;//C++ 17支持
shared_timed_mutex stmux;//C++ 14支持



void ThreadRead(int i)
{//读的部分
	for (;;)
	{
		stmux.lock_shared();//只要没有把互斥锁锁住,共享锁都能进去
		this_thread::sleep_for(500ms);
		cout << i << "Read" << endl;
		stmux.unlock_shared();
		this_thread::sleep_for(1ms);
	}
}

void ThreadWrite(int i)
{//写的部分
	for (;;)
	{
		stmux.lock();//互斥锁锁住,共享锁都进不去
		this_thread::sleep_for(300ms);
		cout << i << "Write" << endl;
		stmux.unlock();
		this_thread::sleep_for(1ms);//防止资源无线使用
	}
}



int main()
{
	//并发三个守护线程
	for (int i = 0; i < 3; i++)
	{
		thread th(ThreadWrite, i);
		th.detach();
	}
	for (int i = 0; i < 3; i++)
	{
		thread th(ThreadRead, i);
		th.detach();
	}
	getchar();
	return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值