Example of QT using a signal slot in multi-threading

Source: Internet
Author: User
Tags thread class

Prior to the thread understanding is not deep, so the thread mechanism of QT is not clear, write an article today to summarize, if there are errors, welcome to point out.

First you need to understand what the thread is, the thread in the code is actually a function, but this function and the main thread of the function run at the same time, write the C language know that the general code is run from the main () function, each thread has an entry function, main () function can be considered as the main thread of the entry function, starting from the main function, the main thread began, write a little bit of code know that the program is starting from the main () function to execute a line down, but sometimes we need to execute a A, a, a-b two functions. The first step in the code is to call the A function, and then the B function, when the a function executes and then executes the B function, not achieving the purpose that we want to execute at the same time. If you put the a function in another thread, then you do not have to wait until the a function is executed, and the B function can begin execution. C++11 has a multi-line libraries, a simple example

Std::thread T (A); B ();

You can write two functions, the function name is a, B. function content can be written as output 10,000 times a (b function can output 10,000 times B, the number of outputs may not be observed), you may find A and B will alternately appear, this is a and b at the same time the proof of execution. Multi-threaded in the graphical interface program is almost necessary, the main thread of the graphical interface program is usually the interface thread, in response to the user's operation, the background thread is used to perform calculations, communications and other operations, if not using multi-threading, the graphical interface will be waiting for the calculation of data (of course, I am talking about a large amount of data, While stuck does not respond to user actions. Here you may have a basic impression of threading.

QT uses the Qthread class in two ways, this online can find a lot of information.

The first: Inherit the Qthread class, write a class (assuming mythread), rewrite the qthread run () function, and the new thread will run the code inside the run (), but be aware that only the code inside the run () function runs in the new thread, So the slot function inside your own Mythread class is bound to the main thread's signal, but as long as it's not running in run () or running in the main thread.

The second: Using Movetothread (), my example code below is the Movetothread () method used. The default run () function in Qthrad enables the event loop (exec ()), so all slot functions for that object that you move to the thread are executed in the new thread and do not block the main thread. Read the example and you'll see. Create a new Qapplication project and change the mainwindow.h to the following code

//Mainwindow.h
#ifndef Mainwindow_h#defineMainwindow_h#include<QApplication>#include<QObject>#include<QEvent>#include<thread>#include<iostream>#include<QThread>#include<QPushButton>#include<QVBoxLayout>#include<QMainWindow>//Network ThreadclassNetworkthread: Publicqobject{Q_object Public: Networkthread () {//Do some initial works;}signals:voidDatacoming (inta);Private: voidMemberfun (); PublicSlots:voidTestslot (); voidSleepslot ();};//Network Thread class//GUI class,run in main threadclassMywidget: Publicqmainwindow{Q_object Public: Qpushbutton*firstbutton,*secondbutton,*Thirdbutton; Qvboxlayout*layout; Qwidget*p; Public: ExplicitMywidget (Qwidget *parent); ~mywidget (); Signals:voidSignalteststart (intA=0); voidstartnetworksleep (); PublicSlots:voidsecondbuttonclicked ();};//GUI class//Csapplication classclassCsapplication: Publicqapplication{Q_object Public: Csapplication (intargcChar*argv[]); Mywidget*Mywindow; Networkthread*NETTHD; Qthread*T; ~csapplication ();};//Csapplication class#endif //Mainwindow_h

Change the main.cpp to the following code and delete the Mainwindow.cpp

//main.cpp#include"mainwindow.h"//Network ThreadvoidNetworkthread::testslot () {std::cout<<"\nin testslot () \ n Thread ID:"&LT;&LT;STD::THIS_THREAD::GET_ID () <<Std::endl; Memberfun ();}voidNetworkthread::memberfun () {std::cout<<"\nin networkthread::memberfun () \nthread ID:"&LT;&LT;STD::THIS_THREAD::GET_ID () <<"\ n"<<Std::endl;}voidNetworkthread::sleepslot () {std::cout<<"In networkthread::sleepslot () \ n Thread ID:"&LT;&LT;STD::THIS_THREAD::GET_ID () <<"\nthen sleep 5 seconds\n"; Qthread::sleep (5); Std::cout<<"Sleepslot () weak up\n"<<Std::endl;}//Network Thread class//GUI class,run in main threadMywidget::mywidget (Qwidget*parent=0) {Firstbutton=NewQpushbutton (TR (" First")); Secondbutton=NewQpushbutton (TR ("Second")); Thirdbutton=NewQpushbutton (TR ("Third")); Layout=Newqvboxlayout; Layout-AddWidget (Firstbutton); Layout-AddWidget (Secondbutton); Layout-AddWidget (Thirdbutton); P=NewQwidget; P-setlayout (layout); Setcentralwidget (P);} Mywidget::~Mywidget () {DeleteFirstbutton; DeleteSecondbutton; DeleteThirdbutton; Deletep; Deletelayout;}voidmywidget::secondbuttonclicked () {emit startnetworksleep (); Std::cout<<"In mywidget::secondbuttonclicked () \ n Thread ID:"&LT;&LT;STD::THIS_THREAD::GET_ID () <<"\ n"<<Std::endl;}//GUI class//Csapplication classCsapplication::csapplication (intargcChar*argv[]): Qapplication (argc,argv) {std::cout<<"\nin csapplication () \nthread ID:"&LT;&LT;STD::THIS_THREAD::GET_ID () <<"\ n"<<Std::endl; Mywindow=NewMywidget (); NETTHD=NewNetworkthread (); T=NewQthread (); Connect (Mywindow-firstbutton,signal (clicked ()), Netthd,slot (Testslot ()), qt::queuedconnection); Connect (Mywindow-secondbutton,signal (clicked ()), Mywindow,slot (secondbuttonclicked ()));    Connect (mywindow,signal (Startnetworksleep ()), Netthd,slot (Sleepslot ()), qt::queuedconnection); NETTHD-Movetothread (t); T-start (); Mywindow-show ();} Csapplication::~csapplication () {DeleteMywindow; DeleteNETTHD; Deletet;}//Csapplication classintMainintargcChar*argv[])    {Csapplication A (argc, argv); returna.exec ();}

Click to run it.

Example of QT using a signal slot in multi-threading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.