C++11线程简述

C++在11版之前貌似是没有线程功能的。

终于在C++11将线程加入进来了,喜大普奔。

     C++11引入了thread类,大大降低多线程使用复杂度,一套代码平台移植,现在C++11中只需使用语言层面的thread可以解决这个问题。

     今天介绍一哈C++11的线程如何运用哦。这里我使用的是Vs2015。

线程头文件

     #include < thread > // 引入线程
     #include < mutex > // 引入线程锁

线程声明

     std::thread testThread( zzz, x, y, …);

          zzz为线程所执行的函数。

          x、y等均为传入参数

     testThread.join(); // 阻塞方式运行

     testThread.detach(); // 非阻塞方式运行

     testThread.get_id(); // 线程id,std::cout << testThread.get_id();

线程锁

     mutex Mutex;
          Mutex.lock(); //加锁
          Mutex.unlock(); //解锁

std::ref和std::cref (与线程无关)

     std::ref 用于包装按引用传递的值。
     std::cref 用于包装按const引用传递的值。

线程睡眠

     this_thread::sleep_for(chrono::minutes(1)); // 睡眠1分钟

     this_thread::sleep_for(chrono::seconds(1)); // 睡眠1秒

     this_thread::sleep_for(chrono::milliseconds(100)); // 睡眠100毫秒

     this_thread::sleep_for(chrono::microseconds(100)); // 睡眠100微秒

     

卖票例子

     1、创建买票类对象

#include <iostream>

#include <thread>
#include <mutex>

using namespace std;

class ThreadTest
{
public:
	//卖票线程1
	void ThreadTest::Thread1(unsigned short);
	//卖票线程2
	void ThreadTest::Thread2(char *);

	ThreadTest();

private:
	//票的剩余数目
	int Sum;

	mutex Mutex;//线程锁
};

     
     2、实现卖票类

#include "ThreadTest.h"

void ThreadTest::Thread1(unsigned short value)
{
	for (;;)
	{
		Mutex.lock();										// 加锁

		--Sum;

		if (Sum < 0)
		{
			printf("Thrad1——票卖完了\n", Sum);
			Mutex.unlock();									// 解锁
			break;
		}
		printf("Thrad1——剩余票数:%d\t%d\n", Sum, value);
		Mutex.unlock();										// 解锁

		this_thread::sleep_for(chrono::milliseconds(10));	// 休息
	}
}


void  ThreadTest::Thread2(char *buf)
{
	for (;;) 
	{
		Mutex.lock();										// 加锁       
		
		--Sum;

		if (Sum < 0) 
		{
			printf("Thrad2——票卖完了\n");
			Mutex.unlock();									// 解锁
			break;
		}
		printf("Thrad2——剩余票数:%d\t%s\n", Sum,buf);

		Mutex.unlock();										// 解锁
		
 		this_thread::sleep_for(chrono::milliseconds(100));	// 休息
	}

	

}

//构造函数
ThreadTest::ThreadTest()
{
	Sum = 200;

	unsigned short Thread1 = 100;
	thread t1(&ThreadTest::Thread1, this, std::ref(Thread1));
	std::cout << "线程t1的id:" << t1.get_id() << std::endl;
	t1.detach();

	char *buf = new char[1024];
	memset(buf, 0, 1024);
	memcpy(buf, "hello,world!\0", 12);
	thread t2(&ThreadTest::Thread2, this, buf);
	std::cout << "线程t2的id:" << t2.get_id() << std::endl;
	t2.join();
	delete buf;
	buf = nullptr;
}

     3、调用

#include "ThreadTest.h"

int main()
{
	//多线程卖票类
	ThreadTest SaleThread;

	system("pause");
	return 0;
}

     
     结果
在这里插入图片描述

     

源码

正在上传源码,稍候。

     

关注

微信公众号搜索"Qt_io_"或"Qt开发者中心"了解更多关于Qt、C++开发知识.。

笔者 - jxd

发布了43 篇原创文章 · 获赞 0 · 访问量 2917

猜你喜欢

转载自blog.csdn.net/automoblie0/article/details/103510098