Hello ALL,
In my program, I first receive data from another machine, then processing the data. Data receiveing is fast, but data processing is relatively time consuming. Hence, I put the code for data processing in a POSIX thread (i am using Red Hat enterpriese linux AS 4). In the main() function, I receive data first. Whevenever a data is received, a new thread for processing the data is created.
In this thread,
http://www.codeguru.com/forum/showthread.php?t=459433
a friend Peled suggested a class, named SynchronizedQueue as shown below. I think the class is great for solving classic producer/consumer problem. However, I do not exactly know how to use it since my poor C++ knowledge. Can anyone help me with this. Please demonstrate how to use the SynchronizedQueue class?
SynchronizedQueue.cpp
#include "SynchronizedQueue.h"
/*
* SynchronizedQueue.h
* Author: Ishay Peled
*/
using namespace std;
SynchronizedQueue::SynchronizedQueue(){
m_iSize = 0;
pthread_mutex_init(&m_ptrMutex,NULL);
pthread_cond_init(&m_ptrCondition, NULL);
}
SynchronizedQueue::~SynchronizedQueue(){
pthread_mutex_destroy(&m_ptrMutex);
pthread_cond_destroy(&m_ptrCondition);
}
void SynchronizedQueue::push(Message* obj){
pthread_mutex_lock(&m_ptrMutex);
m_vctQueue.push_back(obj);
m_iSize++;
if (m_iSize == 1)
pthread_cond_signal(&m_ptrCondition);
pthread_mutex_unlock(&m_ptrMutex);
}
Message* SynchronizedQueue::pop(){
Message* result;
void* res;
pthread_mutex_lock(&m_ptrMutex);
while (m_iSize == 0)
pthread_cond_wait(&m_ptrCondition, &m_ptrMutex);
result = m_vctQueue[0];
m_vctQueue.erase(m_vctQueue.begin());
m_iSize--;
pthread_mutex_unlock(&m_ptrMutex);
return result;
}
int SynchronizedQueue::getSize(){
return m_iSize;
}
SynchronizedQueue.h
#ifndef BUFFER_H
#define BUFFER_H
#include <pthread.h>
#include <string>
#include <vector>
#include "Semaphore.h"
#include "Message.h" //Change this to the data type you're using
using namespace std;
class SynchronizedQueue{
public:
SynchronizedQueue();
~SynchronizedQueue();
void push(Message* obj);
Message* pop();
int getSize();
private:
std::vector<Message*> m_vctQueue;
pthread_mutex_t m_ptrMutex;
pthread_cond_t m_ptrCondition;
int m_iSize;
};
#endif