0

In this code, I am first creating a thread that keeps running always. Then I am creating objects and adding them one by one to a queue. The thread picks up object from queue one by one processes them and deletes them.

class MyClass
{
    public:
        MyClass();
        ~MyClass();
        Process();
};

std::queue<class MyClass*> MyClassObjQueue;

void ThreadFunctionToProcessAndDeleteObjectsFromQueue()
{
    while(1)
    {
        // Get and Process and then Delete Objects one by one from MyClassObjQueue.
    }
}

void main()
{
    CreateThread (ThreadFunctionToProcessAndDeleteObjectsFromQueue);

    int N = GetNumberOfObjects(); // Call some function that gets value of number of objects

    // Create objects and queue them
    for (int i=0; i<N; i++)
    {
        try
        {
            MyClass* obj = NULL;
            obj = new MyClass;
            MyClassObjQueue.push(obj);
        }
        catch(std::bad_alloc&)
        {
            if(obj) 
                delete obj;
        }
    }

    // Wait till all objects have been processed and destroyed (HOW ???)
}

PROBLEM: I am not sure how to wait till all objects have been processed before I quit. One way is to keep on checking size of queue periodically by using while(1) loop and Sleep. But I think it's novice way to do the things. I really want to do it in elegant way by using thread synchronization objects (e.g. semaphore etc.) so that synchronization function will wait for all objects to finish. But not sure how to do that. Any input will be appreciated.

(Note: I've not used synchronization objects to add/delete from queue in the code above. This is only to keep the code simple & readable. I know STL containers are not thread safe)

Atul
  • 3,778
  • 5
  • 47
  • 87
  • You can use a semaphore and mutex, or condvar, to manage the queue, but that does not allow the thread to detect that that its job is over. You could push objects on until you are finished, then push on a 'special' object that tells the thread to finish. I often use a NULL because it cannot be an object pointer and, if there is more than one thread waiting on the queue, it can be pushed back on by its receiving thread before terminating, so serially terminating all the waiting threads without any lifetime issues. – Martin James Mar 09 '15 at 05:51
  • Oh, I misunderstood. OK, push on your objects, then the poison-pill, and wait on a semaphore/condvar/whatever, that the thread signals after receiving the pill, just before it terminates. You could pass the semaphore as part of the thread creation parameter block. – Martin James Mar 09 '15 at 05:55

0 Answers0