c++新特性:多线程

    很高兴c++11的标准库可以#include <thread>了。boost早就提供了类似功能。这时候考虑下开发商、物业公司联合阻碍成立业主委员会的借口之一:

会妨碍事情的正常进展,推断也许他们也是c++的长期使用者:)

1、pthread_xx的封装

    stl提供了(目前)五个头文件以支持多线程:atomic(提供原子操作功能)、thread(线程模型封装)、mutex(互斥量)、condition_variable(条件变量)、future

只使用win32的c++程序员可能对提供的线程库感觉很陌生。事实上,它看起来的确是pthread_xx的c++封装。如果对pthread不熟悉的话,可以参考https://computing.llnl.gov/tutorials/pthreads/

即便如此,在windows下创建一个默认参数的线程已经变得如此简单了:

 

#include <iostream>
#include <thread>

using namespace std;

void thread_1()
{
	cout << "hello from thread_1" << endl;
}

int main(int argc, char **argv)
{
	thread t1(thread_1);
	/**
	join()相当于调用了两个函数:WaitForSingleObject、CloseHandle,事实上,在vc12中也是这么实现的
	*/
	t1.join();
	return 0;
}

 

 

由于在thread的构造函数中调用了bind,线程函数的原型也简单,不用严格写成 void* (*FUN)(void*)的形式了。

甚至可以调用c++的成员函数:

#include <iostream>
#include <thread>

using namespace std;

class thread_c
{
public:
	void thread_1()
	{
		cout << "hello from class member function" << endl;
	}
};

int main(int argc, char **argv)
{
	thread t1(&thread_c::thread_1, thread_c());
	t1.join();
	return 0;
}

没错,封装后的thread class也丢失了一些系统级特性,比如,创建线城时你没法设置参数,习惯使用CREATE_SUSPENDED 参数调用_beginthread的windows开发者可能会特别不习惯。要实现诸如等待的运行方式,mutex、condition_variable这两个头文件就能用上了:

 

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>

using namespace std;

condition_variable cv;
mutex mtx;

void thread_1()
{
	unique_lock<mutex> ulock(mtx);
	cv.wait(ulock);
	cout << "hello from thread_1" << endl;
}

int main(int argc, char **argv)
{
	thread t1(thread_1);
	this_thread::sleep_for(chrono::seconds(1));
	cv.notify_one();
	t1.join();
	return 0;
}

 

condition_variable头文件对应了pthread_cond_xx一簇函数的功能实现。condition_variable::wait接受一个unique_lock<mutex>& 类型的参数。需要注意的是,所有的wait成员函数调用都必须使用同一个"mutex"对象来构造unique_lock(可以由std::unique_lock::mutex()函数返回)pthread_cond_wait的解释要比stl的库文档上对wait函数的解释清楚。mutex对象对条件对象进行保护,调用者要先锁住互斥量传递给wait函数,wait函数把调用线程放到等待条件的线程列表上,然后对互斥量解锁,这样才能再次去锁住mutex对象进行wait操作(试想如果没有这个机制,多个线程同时对条件对象调用wait)。开始等待条件发生。当wait()函数返回的时候,互斥量又要被锁住。

2、future

     此头文件实现了对指定数据提供者提供的数据进行异步访问的机制。里面包含的及个重点类:

     future   能从作为供给源的对象或者函数获取值,如果是不同线程,则同步此操作

     promise  保存能被future对象获取的值

 

#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <string>

using std::string;

class thread_c
{
public:
	void print_int(std::future<string>& fut) {		
		std::cout << "value: " << fut.get() << '\n';
	}
};

int main()
{
	std::promise<string> prom;                
	std::future<string> fut = prom.get_future();  
	thread_c thread_obj;
	std::thread th1(&thread_c::print_int, thread_obj,  std::ref(fut)); 
	prom.set_value("hello future !");                         
	th1.join();	
	return 0;
}

shared_future   接口与future类似(从名称来看是一样的),不同的是它可以拷贝,也可以多次取值。可以通过shared_future的构造函数隐式或者调用future::share


来显式将一个future对象转变成shared_future

 

#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future
#include <string>

using std::string;

class thread_c
{
public:
	~thread_c()
	{
		std::cout << "thread_c object destructed." << std::endl;
	}
public:
	void print_int(std::shared_future<string>& fut) {	
		std::cout << "value: " << fut.get() << '\n';
	}
};

int main()
{
	std::promise<string> prom;                
	std::shared_future<string> fut = prom.get_future();
	thread_c thread_obj;
	const int thread_num = 10;
	std::thread threads[thread_num];
	for (int i = 0; i < thread_num; i++)
	{
		threads[i] = (std::thread(&thread_c::print_int, std::ref(thread_obj), std::ref(fut)) );
	}	
	prom.set_value("hello future !");                         
	// c++11支持的for语法
	for (auto& th : threads)  th.join();
	
	return 0;
}


3、atomic  提供原子操作实现。里面就两个类aotmic、atomic_flag,好像没啥好说的

4、几个函数

     std::call_once      包含在mutex中,看名字也知道,它能保证某个操作只进行一次

 

#include <iostream>       
#include <functional>     
#include <thread>         
#include <future>         
#include <string>

using std::string;

class thread_c
{
protected:
	std::once_flag _once_flag;
public:
	void thread_fun(int thread_no) 
	{	
		std::this_thread::sleep_for(std::chrono::microseconds(1000000));
		std::call_once(_once_flag, std::bind(&thread_c::once_func, this, thread_no));
	}
protected:
	void once_func(int x)
	{
		std::cout << "called by thread " << x << std::endl;
	}
};

int main()
{
	thread_c thread_obj;
	const int thread_num = 10;
	std::thread threads[thread_num];
	for (int i = 0; i < thread_num; i++)
	{
		threads[i] = std::thread(&thread_c::thread_fun, std::ref(thread_obj), i+1) ;
	}                  

	for (auto& th : threads)  th.join();
	
	return 0;
}


std::async     包含在future中。它能异步执行某个函数,将结果以future对象的形式返回   

 

#include <iostream>       
#include <functional>     
#include <thread>         
#include <future>         

using std::cout;
using std::endl;

class thread_c
{
public:
	int thread_fun(int num)
	{
		cout << "calculating....." << endl;
		int count = num;
		for (int i = 0; i < num; i++)
		{
			count++;
		}
		cout << "end calculate" << endl;
		return count;
	}
};

int main()
{
	thread_c thread_obj;	
	std::future<int> ret = std::async(std::bind(&thread_c::thread_fun, &thread_obj, 10000));
	cout << "async get value = " << ret.get() << endl;

	return 0;
}

以上代码在visual studio 2013编译,gcc-4.9.2对c++11提供了完整的支持。如果两个编译都没安装,可以使用c++的在线编译器

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章