Qt文档指出信号和槽可以是direct,queued和auto.
它还声明,如果拥有插槽的对象'生命'在与拥有信号的对象不同的线程中,则发出此类信号就像发布消息一样 - 信号发出将立即返回,并且将在目标线程的事件循环中调用slot方法.
不幸的是,文档没有说明"生命"代表的是没有例子可用.我试过以下代码:
main.h:
class CThread1 : public QThread
{
Q_OBJECT
public:
void run( void )
{
msleep( 200 );
std::cout << "thread 1 started" << std::endl;
MySignal();
exec();
}
signals:
void MySignal( void );
};
class CThread2 : public QThread
{
Q_OBJECT
public:
void run( void )
{
std::cout << "thread 2 started" << std::endl;
exec();
}
public slots:
void MySlot( void )
{
std::cout << "slot called" << std::endl;
} …Run Code Online (Sandbox Code Playgroud) 使用moveToThread在Qt中将对象从一个线程移动到另一个线程是什么意思?甚至在使用moveToThread之前,一切似乎都工作,moveToThread将对象从一个线程(GUI线程)移动到另一个线程(工作),Qt:connect调用对象上的相应插槽.
由于对象所在的位置,GUI线程或工作线程,有什么区别吗?
编辑:我做了一个小程序,但我不明白QThread如何与Signal和插槽功能一起工作,如果你能解释一下moveToThread的用法,我将不胜感激
#include <QtGui/QApplication>
#include <QPushButton>
#include <QHBoxLayout>
#include <QLineEdit>
#include <QString>
#include "mythread.h"
//GUI calls a thread to do some job and sub update the text box once it is done
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
QHBoxLayout * pH = new QHBoxLayout(&w);
QPushButton * pushButton = new QPushButton("asdad");
QLineEdit * lineEdit = new QLineEdit("AAA");
pH->addWidget(pushButton);
pH->addWidget(lineEdit);
w.setLayout(pH);
w.show();
MyThread thread;
qDebug("Thread id %d",(int)QThread::currentThreadId());
QObject::connect(pushButton,SIGNAL(clicked()),&thread,SLOT(callRun())) ;
QObject::connect(&thread,SIGNAL(signalGUI(QString)),lineEdit,SLOT(setText(QString)));
return a.exec();
}
#ifndef MYTHREAD_H
#define …Run Code Online (Sandbox Code Playgroud) 假设我们在QObject-deriving类中编写了一个非const方法:
class MyClass : public QObject {
int x;
public:
void method(int a) {
x = a; // and possibly other things
};
};
Run Code Online (Sandbox Code Playgroud)
我们希望使该方法成为线程安全的:意味着从任意线程调用它,并且同时从多个线程调用它,不应该引入未定义的行为.
Qt提供了哪些机制/ API来帮助我们使该方法具有线程安全性?
Qt的哪些机制/ API可以在方法执行"其他事情"时使用?
是否可以对"其他事物"进行分类,以便为使用Qt特定的机制/ API提供信息?
非主题是C++标准本身提供的机制,以及确保线程安全的通用/非Qt特定方式.