who knows, maybe someday this template could be part of the wxWidgets release.. with some modifications of course.
here it goes:
wxMailbox.hpp
Code: Select all
#ifndef _wxMailbox_h_
#define _wxMailbox_h_
#include <wx/wx.h>
#include <vector>
/****************************************************
wxMailbox is useful for working with threads.
Elements are passed by copy.
*****************************************************/
template <class T>
class wxMailbox
{
public:
//constructor: max cantidad pendientes, y si debe hacer delete de los que restan al destruirse
wxMailbox( unsigned int maxCount = 10 );
wxMailbox::~wxMailbox();
//Inserts an element at the end of the list
bool Put( T &element );
//Tries to get an element out of the Mailbox
bool TryGet( T &element );
private:
wxMutex *m_mutex; //mutex for Put & Get
std::vector< T > m_vector; //maybe not the most efficient allocator
unsigned int m_maxElements;
};
#include "../../common/wxMailbox.tpp" //implementations
#endif
Code: Select all
#include "wxMailbox.hpp"
template <class T>
wxMailbox<T>::wxMailbox( unsigned int maxCount )
{
m_maxElements = maxCount;
m_mutex = new wxMutex();
}
template <class T>
bool wxMailbox<T>::Put( T& element )
{
//lock mutex
wxMutexLocker lock( *m_mutex );
//max size? => out of here
if ( m_vector.size() > m_maxElements-1 )
return false;
//push!
m_vector.push_back( element );
return true;
}
template <class T>
bool wxMailbox<T>::TryGet( T& element )
{
wxMutexLocker lock( *m_mutex );
//empty?
if ( m_vector.empty() )
return false;
//copy
element = m_vector[0];
//erase
m_vector.erase( m_vector.begin() );
return true;
}
template <class T>
wxMailbox<T>::~wxMailbox()
{
//finally..
delete m_mutex;
}
Any ideas welcomed,
thanks again to everyone who helps building wxWidgets!
Carlos