简单的UDP多线程模型

原创
2016/08/24 19:33
阅读数 574

和Lite2D项目中的网络线程和主线程 交互方式 差不多

在这里,队列是线程安全的,


#include <iostream>
#include <list>
#include <string>
#include <algorithm>
#include <vector>
#include <thread>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include "windows.h"
#include <functional>
#include "direct.h"
#include <map>
#include <memory>
#include <queue>
#include <condition_variable>
#include <mutex>

using namespace std;

#define  LOCK(WHAT)   std::unique_lock<std::mutex> locker(WHAT);

template<class T>
class QueueThreadSafe
{
public:
	void push(T &t)
	{
		LOCK(this->_mutex);
		this->_queue.push(t);
	}
	T front()
	{
		LOCK(this->_mutex);
		T & ret = this->_queue.front();
		this->_queue.pop();
		return ret;
	}

	bool empty()
	{
		LOCK(this->_mutex);
		bool ret = this->_queue.empty();
		return ret;
	}
private:
	std::queue<T>  _queue;
	std::mutex _mutex;

};


class UDPClient
{
public:
	void send(char *buffer)
	{

		LOCK(this->_mutex);

		reqs.push(buffer);

		this->_cond.notify_all();
	}
	void loop()
	{
		while (this->isRun)
		{
			LOCK(this->_mutex);

			if (this->reqs.empty() == true)
			{//如果队列为空,那么等待唤醒
				this->_cond.wait(this->_mutex);
			}

			cout << "send :" << reqs.front() << endl;
		}
	}

	bool isRun = true;
	std::mutex _mutex;
	QueueThreadSafe<char*> reqs;
	std::condition_variable_any _cond;
};


static  UDPClient* instance;

static void workThreadFunc()
{
	instance = new UDPClient;
	instance->loop();
}


int main()
{

	std::thread t(workThreadFunc);

	t.detach();


	char str[100];
	int index = 0;

	while (true)
	{
		//	Sleep(1);
		sprintf(str, "%d", index++);
		instance->send(str);
	}

	system("pause");

	return 0;
}

 

 

展开阅读全文
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部