Examples of Multithreading

Programming

Multithreading is a specialized form of multitasking and multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based.

Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. 

In this article, I would like to recount an example of how multithreading helped me. The task consisted of writing an instrument of automatic definition for a device connecting to the serial port. The decision is the code that questions all available serial ports about the existence of a connection to the device we need. But, the nuance is in that, the program will not solve other tasks and react to user actions, until it (program) is waiting for connection, questioning ports.

To realize a new thread in Qt you have to create a new class, the descendant of the QThread class and override the method in it. 

class ConnectToSerial : public QThread 
{
public:
ConnectToSerial() {}

void run() {
isRun = true;
while(isRun){
// The code of questioning serial ports


msleep(200); // The delay in microseconds to get the answer from device, which is likely connect to serial port.
}
};
void stop() {
isRun = false;
};

private:
volatile bool isRun = false;
};

The example of ConnectToSerial class is created in the main program class. To run the method run() use start method start(). This method has already realized in QThread class and runs the method run()in a new thread. Remember! New thread will not be created if you call run()directly from the main class.

class MainWindow : public QMainWindow
{
public:
MainWindow(){
serial.start(); //  New thread is running, and the main program continues to run.
};
private slot:
on_init(){ // The slot that is called when getting the initialization answer from the device we are interested in
serial.stop(); // The thread is finished
};
private:
ConnectToSerial serial;
}

On running the MainWindow, the poll of serial port is running. The availability of connection the device we need is identified in the MainWindow class by calling slot on_init(). After this is the ports’ polling is finished by the starting method stop().
Multithreading helps us create the program that performs time-consuming actions without creating any discomfort to the user while working with a graphic interface.

See also: Common PHP Design Patterns

Comments