Search code examples
c++simulationstdvectorpriority-queue

How does this code work? Specifically, the WorkerCompare struct


(Sorry if this question sounds vague. I'll add more information if needed.)

The task of the program is to simulate parallel processing. One solution I found on the internet contains this code which works but I don't know how. Specifically, why and how WorkerCompare was used:

class Worker {
    public:
        int id;
        long long nextFreeTime;
        Worker (int id) {
            this->id = id;
            nextFreeTime = 0;
        }
};

struct WorkerCompare {
    bool operator()(const Worker &w1, const Worker &w2) const {
        if(w1.nextFreeTime == w2.nextFreeTime)
            return w1.id > w2.id;
        else
            return w1.nextFreeTime > w2.nextFreeTime;
    }
};

This code was mainly used in this function:

void AssignJobs() {
    assigned_workers_.resize(jobs_.size());
    start_times_.resize(jobs_.size());
    priority_queue<Worker, vector<Worker>, WorkerCompare> pq;
    for(int i = 0; i < num_workers_; i++) {
        pq.push(Worker(i));
    }
    for (int i = 0; i < jobs_.size(); i++) {
        Worker freeThread = pq.top();
        pq.pop();
        assigned_workers_[i] = freeThread.id;
        start_times_[i] = freeThread.nextFreeTime;
        freeThread.nextFreeTime += jobs_[i];
        pq.push(freeThread);
    }
  }

It adds elements to the vectors assigned_workers_ and start_times_ which lists the thread used to do a process as well as at what time the process started.

The full source code can be seen here.


Solution

  • priority_queue<Worker, vector<Worker>, WorkerCompare> pq;
    

    I assume that this is the std::priority_queue from the standard library.

    Priority queues work by comparing elements. That is what WorkerCompare is used for. It compares objects of type Worker.