Search code examples
qtqt4operating-system

How to implement "first come first served" scheduling algorithm using threading in Qt C++ programming?


I wish to add processes to a dynamic list then schedule those processes using the "first come first served" scheduling algorithm. The scheduling algorithm should only run a max of 5 processes concurrently and when a process has been terminated it should it should emit a signal to indicate termination.

Then when a process has been terminated, another process should be scheduled by the scheduling algorithm once there are processes in the queue.

Note also that each process has access to a shared list of integer which only one process can access at a time. I already know how to do this part by locking the shared integer list using QMutex. Ideally, I am seeking an example, so I can understand it.

//mutex example
QMutex mutex
while(!mutex->tryLock()){
    //enter code here
}
this->performTask(); // 
mutex.unlock();

Solution

  • You will have 5 instances of a class that extends QThread. Each class will execute a QProcess and wait for it to finish.

    class MyThread : public QThread
    {
    public:
        MyThread(MyScheduler& aScheduler)
        :   iScheduler(aScheduler)
        {
        }
    
        void ExecuteProgram(const QString& aProgramName)
        {
            iProgramName = aProgramName;
            start();
        }
    
        void run()
        {
            iProcess.start(iProgramName);
            iProcess.waitForFinished(-1);
            iScheduler.SignalProgramTerminated(this);
        }
    
    private:
        MyScheduler& iScheduler;  // This is your FCFS scheduler.
        QString iProgramName;
        QProcess iProcess;
    };
    

    (I haven't compiled this but it should give you some headway).