多线程编程

本文深入探讨了C++中的多线程编程,包括join()和detach()函数的使用,线程的函数化,以及joinable()函数检查线程状态。此外,还详细介绍了原子操作、互斥锁和条件变量在确保并发安全中的作用。示例代码展示了如何实现同步和等待线程结束,以及如何利用try_lock()实现精细的锁控制。
摘要由CSDN通过智能技术生成

join()函数

等待当前线程结束
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

detach()函数

在这里插入图片描述
在这里插入图片描述

move()函数

在这里插入图片描述

函数线程化

class Object
{
private:
	int value;
public:
	Object(int x=0):value(x){}
	~Object(){}
	void run()//函数存在this指针
	{
		cout << "Object run" << endl;
	}
	static void fun(int x)//把静态函数线程化
	{
		Object obj(x);//对象的某个方法通过这种方式,仍然可以线程化
		obj.run();
		cout << "static fun" << endl;
	}
};
//全局函数线程化
int main()
{
	std::thread tha(Object::fun, 5);//静态函数没有this指针,如果函数没有形参,这就不需要加实参
	tha.join();
	cout << endl;
}
#if 0
//类的成员函数线程化
int main()
{
	Object obj;
	std::thread thobj(&Object::run, &obj);//必须给参数
	thobj.join();
	cout << "main end" << endl;
}
#endif 

joinable()函数

在这里插入图片描述
和函数关联有资源为1,没有关联为0

void foo()
{
	std::this_thread::sleep_for(std::chrono::seconds(1));
	cout << "foo end" << endl;
}
int main()
{
	std::thread t;
	cout << "befor starrting,joinable" << t.joinable() << endl;
	t = std::thread(foo);
	cout << "after starting,joinable" << t.joinable() << endl;
	t.join();
	cout << "after joining" << t.joinable() << endl;
	
	cout << t.hardware_concurrency() << endl;//获取线程的逻辑处理数
	cout << std::thread::hardware_concurrency() << endl;
	return 0;
}

在这里插入图片描述

在这里插入图片描述
练习:

int funa(int n, int& x)
{
	for (int i = 0; i <= n; i ++ )
	{
		cout << "thread funa" << endl;
		std::this_thread::sleep_for(std::chrono::microseconds(100));
	}
	x = n;
	cout << "thread funa_end()" << endl;
	return n;
}

int main()
{
	int x = 10;
	std::thread tha(funa, 5, std::ref(x));
	for (;;)
	{
		if (tha.joinable())
		{
			break;
		}
		cout << "wait thread..." << endl;
		std::this_thread::sleep_for(std::chrono::microseconds(1000));
	}
	tha.join();//等待线程结束
	return 0;
}

在这里插入图片描述

原子操作

std::atomic_int  g_num = 0;//设置为原子操作
void print(int id)
{
	for (int i = 0; i < 5; i++)
	{
		++g_num;//设为原子操作后,这三步就不可分离
		//mov eax g_num
		//add eax,1
		//g_num,eax
		cout << "id:" << id << "==>" << g_num << endl;
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	std::thread tha(print, 0);
	std::thread thb(print, 1);
	tha.join();
	thb.join();
	cout << "main end" << endl;
}	

互斥锁

int g_num = 1;
std::mutex mtx;
void print(int id)
{
	for (int i = 0; i < 5; i++)
	{
		mtx.lock();//加锁
		++g_num;//设为原子操作后,这三步就不可分离
		//mov eax g_num
		//add eax,1
		//g_num,eax
		cout << "id:" << id << "==>" << g_num << endl;
		mtx.unlock();//解锁
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

在这里插入图片描述

宏观上是同时执行,微观上是交替执行

try_lock()函数

在这里插入图片描述
在这里插入图片描述

作用域锁

在这里插入图片描述

int g_num = 1;
std::mutex mtx;
void print(int id)
{
	for (int i = 0; i < 5; ++i)
	{
		std::lock_guard<std::mutex>lock(mtx);
		++g_num;
		cout << id << "-->" << g_num << endl;
		std::this_thread::sleep_for(std::chrono::microseconds(200));
	}
}
int main()
{
	std::thread tha(print, 0);
	std::thread thb(print, 1);
	tha.join();
	thb.join();
	return 0;
}

条件变量

在这里插入图片描述
循环打印ABC

std::mutex mx;
std::condition_variable cv;
int isReady = 0;
const int n = 10;
void print_A()
{
	std::unique_lock<std::mutex>lock(mx);
	int i = 0;
	while (i < n)
	{
		while (isReady != 0)
		{
			cv.wait(lock);//阻塞当前线程并释放锁
		}
		cout << "A" << endl;
		isReady = 1;
		++i;
	    std:: this_thread::sleep_for(std::chrono::microseconds(100));
		cv.notify_all();
	}
}
void print_B()
{
	std::unique_lock<std::mutex>lock(mx);
	int i = 0;
	while (i < n)
	{
		while (isReady != 1)
		{
			cv.wait(lock);
		}
		cout << "B" << endl;
		isReady = 2;
		++i;
		std::this_thread::sleep_for(std::chrono::microseconds(100));
		cv.notify_all();
	}
}
void print_C()
{
	std::unique_lock<std::mutex>lock(mx);
	int i = 0;
	while (i < n)
	{
		while (isReady != 2)
		{
			cv.wait(lock);
		}
		cout << "C" << endl;
		isReady = 0;
		++i;
		std::this_thread::sleep_for(std::chrono::microseconds(100));
		cv.notify_all();//将等待队列中线程全部唤醒
		}
}
int main()
{
	thread tha(print_A);
	thread thb(print_B);
	thread thc(print_C);
	tha.join();
	thb.join();
	thc.join();
	return 0;
}

注意:内层while循环控制精准唤醒,不可改为if语句(在线程全部唤醒之后,不能保证下一次就是B线程能获得锁,也可能是C获得,所以这里必须用while进行控制)
循环打印奇数和偶数

std::mutex mx;
std::condition_variable cv;
int g_num = 1;


const int n = 10;
void print_A()
{
	std::unique_lock<std::mutex>lock(mx);
	int i = 0;
	while (i < n)
	{
		while (g_num % 2 != 1)
		{
			cv.wait(lock);
		}
		//cv.wait(lock,[]()->bool {return number%2==1}
		cout << "A:"<<g_num << endl;
		i++;
		g_num += 1;
		std::this_thread::sleep_for(std::chrono::microseconds(200));
		cv.notify_all();
	}
}
void print_B()
{
	std::unique_lock<std::mutex>lock(mx);
	int i = 0;
	while (i < n)
	{
	    while (g_num % 2 != 0)
		{
			cv.wait(lock);
		}
		//cv.wait(lock,[]()->bool {return number%2==0}
		cout << "B:"<<g_num << endl;
		i++;
		g_num += 1;
		std::this_thread::sleep_for(std::chrono::microseconds(200));
		cv.notify_all();
	}
}

int main()
{
	thread tha(print_A);
	thread thb(print_B);
	tha.join();
	thb.join();
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值