Me gustaría crear una clase cuyos métodos se puedan invocar desde varios subprocesos. pero en lugar de ejecutar el método en el hilo del que se llamó, debe realizarlos todos en su propio hilo. No es necesario devolver ningún resultado y no debe bloquear el hilo de llamada.Event/Task Queue Multithreading C++
Un primer intento Implementación que he incluido a continuación. Los métodos públicos insertan un puntero de función y datos en una Cola de trabajos, que luego recoge el hilo del trabajador. Sin embargo, no es particularmente bonito el código y agregar nuevos métodos es engorroso.
Idealmente, me gustaría utilizar esto como una clase base que puedo agregar fácilmente métodos (con un número variable de argumentos) con la duplicación mínima de hastle y código.
¿Cuál es la mejor manera de hacerlo? ¿Hay algún código disponible que haga algo similar? Gracias
#include <queue>
using namespace std;
class GThreadObject
{
class event
{
public:
void (GThreadObject::*funcPtr)(void *);
void * data;
};
public:
void functionOne(char * argOne, int argTwo);
private:
void workerThread();
queue<GThreadObject::event*> jobQueue;
void functionOneProxy(void * buffer);
void functionOneInternal(char * argOne, int argTwo);
};
#include <iostream>
#include "GThreadObject.h"
using namespace std;
/* On a continuous loop, reading tasks from queue
* When a new event is received it executes the attached function pointer
* It should block on a condition, but Thread code removed to decrease clutter
*/
void GThreadObject::workerThread()
{
//New Event added, process it
GThreadObject::event * receivedEvent = jobQueue.front();
//Execute the function pointer with the attached data
(*this.*receivedEvent->funcPtr)(receivedEvent->data);
}
/*
* This is the public interface, Can be called from child threads
* Instead of executing the event directly it adds it to a job queue
* Then the workerThread picks it up and executes all tasks on the same thread
*/
void GThreadObject::functionOne(char * argOne, int argTwo)
{
//Malloc an object the size of the function arguments
int argumentSize = sizeof(char*)+sizeof(int);
void * myData = malloc(argumentSize);
//Copy the data passed to this function into the buffer
memcpy(myData, &argOne, argumentSize);
//Create the event and push it on to the queue
GThreadObject::event * myEvent = new event;
myEvent->data = myData;
myEvent->funcPtr = >hreadObject::functionOneProxy;
jobQueue.push(myEvent);
//This would be send a thread condition signal, replaced with a simple call here
this->workerThread();
}
/*
* This handles the actual event
*/
void GThreadObject::functionOneInternal(char * argOne, int argTwo)
{
cout << "We've made it to functionTwo char*:" << argOne << " int:" << argTwo << endl;
//Now do the work
}
/*
* This is the function I would like to remove if possible
* Split the void * buffer into arguments for the internal Function
*/
void GThreadObject::functionOneProxy(void * buffer)
{
char * cBuff = (char*)buffer;
functionOneInternal((char*)*((unsigned int*)cBuff), (int)*(cBuff+sizeof(char*)));
};
int main()
{
GThreadObject myObj;
myObj.functionOne("My Message", 23);
return 0;
}
Estaba buscando boost :: future, pero como no forma parte de una versión de boost lanzada, tuve que recurrir a mi ACE de confianza :-) – lothar
La biblioteca de futuros formará parte de Boost 1.41. También está disponible como parte de mi implementación de la biblioteca de hilos C++ 0x en http://www.stdthread.co.uk –
Gracias, Anthony. Encantado de saber de ti :) –