In QT multi-threaded programming, you can use signals and slots for thread Communication. The following is a simple example.
The program implements a thread to customize a signal and slot, timing 1 seconds to send a signal, slot response after printing a message.
[cpp] View plain copy 650) this.width=650; "src=" https://code.csdn.net/assets/CODE_ Ico.png "width=" "height=" "alt=" on code to view the chip "style=" border:none; "/>650" this.width=650; "src=" HTTPS ://code.csdn.net/assets/ico_fork.svg "width=" "height=" "alt=" derived from my Code slice "style=" border:none; "/>
#include <QtCore/QCoreApplication>
#include <QThread>
#include <stdio.h>
class MyThread: public Qthread
{
Q_object
public :
MyThread ();
void Stop ();
Private :
BOOL isrunning;
void Run ();
public slots:
void showmsg ();
Signals:
void msg ();
};
Mythread::mythread ()
{
-
isrunning = true ;
Connect (This, SIGNAL (msg ()),This, SLOT (showmsg ()), Qt::D irectconnection);
}
void mythread::showmsg ()
{
printf ("hello!\n");
}
void Mythread::run ()
{
while (isrunning)
{
Sleep (1);
Emit msg ();
}
printf ("exit!\n");
}
void mythread::stop ()
{
IsRunning = false;
}
int Main (int argc, char *argv[])
{
Qcoreapplication a (argc, argv);
MyThread mthread;
Mthread.start ();
while (1)
{
if (getchar () = =' B ')
{
Mthread.stop ();
Mthread.wait ();
break ;
}
}
return a.exec ();
}
#include "main.moc"
When compiling in QT creator, you need to compile with "qmake" to generate the MOC File. Then compile with the build Project.
PS:QT Meta-object System
In QT multi-threaded programming, you can use signals and slots for thread communication