I put up an simple example to illustrate my question. Here is the base class.
#include <mutex>
#include <atomic>
class Task
{
public:
Task()
{
Empty.store(true);
}
std::mutex Access;
std::atomic<bool> Empty;
virtual void Work() = 0;
};
This is the derived class.
#include <stdlib.h>
class ExampleTask : public Task
{
public:
void Work()
{
for(int i = 0; i < 16; ++i)
{
Data[i] = rand();
}
}
private:
int Data[16];
};
As you can see, this example is about tasks or jobs which will be done asynchronously. Imagine, there is a queue of Task
s to do and a bunch of worker threads, maybe one for each CPU core on the target machine.
The task queue stores the tasks casted to their base class, so that the worker threads can just pick up the next job from the queue and call Work()
.
std::list<Task*> Queue;
ExampleTask *example = new ExampleTask();
Queue.push_back((Task*)example);
A worker thread would then fetch the first task, remove it from the queue, and work on it.
while(true)
{
Task *current = Queue.front();
Queue.erase(Queue.begin());
current->Work();
}
Would this concept work? Can Data
be accessed when current->Work()
is called, even if I deal with a pointer to the base class?