C++11多线程学习(2)自旋锁任务队列

使用上一节的原子数构造成的自旋锁完成了一个任务队列的模型。因为condition_variable只能和mutex配合,想要让他和别的锁配合就要用condition_variable_any

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
class Mylock
{
private:
	atomic_flag _lock;
public:
	Mylock()
	{
		_lock.clear();
	}
	void lock()
	{
		while(_lock.test_and_set())
			;
	}
	void unlock()
	{
		_lock.clear();
	}
};
class Task
{
private:
	int _index;
public:
	Task(int index):_index(index)
	{ }
	void work()
	{
		cout<>_queue;
	int _threadnum;
	int _running;
	vector_threads;
	static TaskQueue*_instance;
	TaskQueue(int threadnum=4):_threadnum(threadnum),_running(false)
	{ }
public:
	
	static TaskQueue* getInstance()
	{
		if(!_instance)
			_instance=new TaskQueue();
		return _instance;
	}
	void start()
	{
		_running=true;
		for(int i=0;i<_threadnum;i++)
			_threads.push_back(thread(&TaskQueue::run,this));
		
	}
	void push(shared_ptrtask)
	{
		lock_guardlg(_splock);
		_queue.push(task);
		cv.notify_one();
	}
private:
	shared_ptrtake()
	{
		unique_lockul(_splock);
		cv.wait(ul,[this]{ return !_queue.empty(); });
		shared_ptrspt;
		if(!_queue.empty())
		{
			spt=_queue.front();
			_queue.pop();
			return spt;
		}
		return NULL;
	}
	void run()
	{
		while(_running)
		{
			shared_ptrtask=take();
			if(task)
				task->work();
		}
	}
};
TaskQueue* TaskQueue::_instance=NULL;
int main ()
{
	TaskQueue* tq=TaskQueue::getInstance();
	for(int i=0;i<10000;i++)
	{
		shared_ptrsp=make_shared(i);
		tq->push(sp);
	}
	tq->start();
	sleep(10000);
}

如果任务很多执行很快的情况下,可以想象自旋锁是很有优势的,它不需要频繁的陷入内核,但是相反如果任务复杂,或者任务并不多的情况下,自旋锁会把大量的时间浪费在忙等待上。

你可能感兴趣的:(C++11多线程)