标签:des style color os io ar for 数据 sp
采用pthread_cond_timedwait函数,条件到了,线程即会被join,可及时唤醒线程。实现的如下:
#include <stdio.h>
pthread_mutex_lock(&mutex); |
pthread_cond_timedwait()函数阻塞住调用该函数的线程,等待由cond指定的条件被触发(pthread_cond_broadcast() or pthread_cond_signal())。
当pthread_cond_timedwait()被调用时,调用线程必须已经锁住了mutex。函数pthread_cond_timedwait()会对mutex进行【解锁和执行对条件的等待】(原子操作)。
关于socket数据的队列实现:
#include <deque>#include <sys/types.h>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <stdio.h>
#include "cocos2d.h"
using namespace std;
template<class DataType> //接收的数据队列,对队列的数据操作是需要线程互斥的
class Queue
{
public:
Queue():_nready(0)
{
pthread_mutex_init(&_mutex, NULL);
pthread_cond_init(&_cond, NULL);
}
~Queue()
{
pthread_mutex_lock(&_mutex);
_queue.clear();
pthread_mutex_unlock(&_mutex);
pthread_mutex_destroy(&_mutex);
pthread_cond_destroy(&_cond);
}
void put_msg(DataType d)
{
pthread_mutex_lock(&_mutex);
_queue.push_back(d);
_nready++;
pthread_mutex_unlock(&_mutex);
pthread_cond_signal(&_cond);
}
void push_msg(DataType d)
{
pthread_mutex_lock(&_mutex);
_queue.push_back(d);
_nready++;
pthread_mutex_unlock(&_mutex);
}
void get_msg(DataType &d)
{
pthread_mutex_lock(&_mutex);
while (_nready == 0)
pthread_cond_wait(&_cond, &_mutex);
_nready--;
d = _queue.front();
_queue.pop_front();
pthread_mutex_unlock(&_mutex);
}
int pop_msg(DataType &d)
{
pthread_mutex_lock(&_mutex);
if (_nready == 0)
{
pthread_mutex_unlock(&_mutex);
return -1;
}
_nready--;
d = _queue.front();
_queue.pop_front();
pthread_mutex_unlock(&_mutex);
return 0;
}
int get_msg(DataType &d, int sec)
{
timeval now;
struct timespec timeout;
int retval = 0;
pthread_mutex_lock(&_mutex);
while (_nready == 0) //在一定时长保持等待数据
{
gettimeofday(&now, NULL);
timeout.tv_sec = now.tv_sec + sec;
timeout.tv_nsec = now.tv_usec * 1000;
retval = pthread_cond_timedwait(&_cond, &_mutex, &timeout);
if (retval == ETIMEDOUT)
{
pthread_mutex_unlock(&_mutex);
return -1;
}
}
_nready--;
d = _queue.front();
_queue.pop_front();
pthread_mutex_unlock(&_mutex);
return 0;
}
void reset_msg()
{
pthread_mutex_lock(&_mutex);
_queue.clear();
_nready = 0;
pthread_mutex_unlock(&_mutex);
}
private:
int _type;
pthread_cond_t _cond;
int _nready;
pthread_mutex_t _mutex;
deque<DataType> _queue;
};
#endif /* _QUEUE_H_ */
标签:des style color os io ar for 数据 sp
原文地址:http://blog.csdn.net/zhuanzhuwanmei/article/details/39076971