crash. QObject::connect in a constructor of a static object instance - c++

I'm trying to find out why my app crashes for the whole day. A picture worth thousands of words, so take a look at this code. Header:
class SandboxedAppStat : public QObject
{
Q_OBJECT
private slots:
void pidsTimerTimeout();
public:
QTimer m_PidsTimer;
SandboxedAppStat(QObject *parent = NULL);
};
class SandboxedApp : public QObject
{
Q_OBJECT
private:
static SandboxedAppStat SandboxedAppStat1;
};
Implementation:
void SandboxedAppStat::pidsTimerTimeout()
{
qDebug() << "whatever";
}
SandboxedAppStat::SandboxedAppStat(QObject *parent)
: QObject(parent)
{
bool b = QObject::connect(&m_PidsTimer, SIGNAL(timeout()),
this, SLOT(pidsTimerTimeout()));
m_PidsTimer.start(500);
}
SandboxedAppStat SandboxedApp::SandboxedAppStat1;
Actually what I'm trying to do, is to simulate static constructor behavior in C++. I want
QObject::connect(&m_PidsTimer, SIGNAL(timeout()),
this, SLOT(pidsTimerTimeout()));
m_PidsTimer.start(500);
to be called as soon as the static member SandboxedAppStat1 initializes. That's why the code shown above is in the constructor of SandboxedAppStat.
However, my problem is that when I run the program, it crashes as soon as it reaches the line connect(&m_PidsTimer, SIGNAL(timeout()), this, SLOT(pidsTimerTimeout()));
with error code c0000005 (access violation I guess).
here's the screenshot http://dl.dropbox.com/u/3055964/Untitled.gif
If I declare SandboxedAppStat as a non static variable, then there is no crash and no errors. everything works fine.
First I thought that crash reason could be the fact that, static members are initialized too early for QObject::connect to be able to be called, that's why I updated SandboxedAppStat constructor with the following code:
auto *t = this;
QtConcurrent::run([&] () {
Sleep(3000);
bool b = QObject::connect(&(t->m_PidsTimer),
SIGNAL(timeout()), t, SLOT(pidsTimerTimeout()));
t->m_PidsTimer.start(500);
});
As you can see, QObject::connect executes after 3 seconds when static SanboxedAppStat is initialized, but this didn't help either, the program crashes after 3 seconds.
I'm really confused, I don't understand what can be the cause of this problem. Can't we use signal/slots in a static object instances?
I'm using Qt 4.8.0 with MSVC 2010. Thanks
UPDATE
Here's a simple project, consisting of only one header and one source file (as HostileFork suggested) to reproduce the crash. http://dl.dropbox.com/u/3055964/untitled1.zip

Are you looking for periodic calling of your pidsTimerTimeout slot or just once during construction?
If you're looking to just receive a signal once your class has been constructed try using QTimer::singleShot or QMetaObject::invokeMethod if you don't require continuous time outs. Like all signals the single shot will only be acted upon once the window system's event queue have been processed which can have a small delay on the execution of your slot.
MyClass::MyClass()
{
// Using a zero singles shot.
QTimer::singleShot( 0, this, SLOT( initialized() ) );
// or using invoke method.
QMetaObject::invokeMethod( this, "initialized", Qt::QueuedConnection );
}
Pretty sure we use this code in the office and we have success with static objects.

Related

How can I emit a signal of another instance from _clicked() event?

the runnable project is here:
enter link description here
I sincerely glad to have your detail answers to solve this, but I am still confusing on this issue:
case 1: changing socket_session as a member variable of mainwindow
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
SocketThread* socket_session;
private:
...
But this is not the solution to access setFlag, even after I change the `Form1::on_qpushButton__set_white_level_0_clicked()' function like this:
void Form1::on_qpushButton__set_white_level_0_clicked() {
qDebug() <<"clicked()";
socket_session->setThreadFlag(true);
}
Still it doesn't make sense because form1 instance doesn't have "the" instance of socket_thread which has been instantiated from mainwindow.
There's a solution I think is making another class that includes all instances that I want to use from inside of mainwindow but I don't think that is a good one because I am using thread and accessing a global big instance class that includes all of them to be "shared" is not a good idea for someone like me.
#include <form1.h>
#include <ui_form1.h>
#include "socketthread.h"
Form1::Form1(QWidget *parent) :
QWidget(parent),
ui(new Ui::Form1) {
ui->setupUi(this);
}
Form1::~Form1() {
delete ui;
}
void Form1::on_qpushButton__set_white_level_0_clicked() {
qDebug() <<"clicked()";
socket_session->setThreadFlag(true);
}
enter image description here
I know I am lack of understanding about this but, do I wanna make something nobody does...? I think everyone wants to separate all objects and their methods clearly and communicate via signals or calling functions from delivered object instances...
case 2: ... let me try how you suggested make possible first...
I can read C++ code and overall structure, but I don't know why I have to struggle with this, so please help me, dear Guru.
On socketthread.h :
class SocketThread : public QThread {
Q_OBJECT
public:
QTcpSocket *socket_session;
SocketThread();
~SocketThread(){}
bool connectToServer(QString, int);
void sendData(const char*, int, int);
void run(void);
private:
QString message;
volatile bool threadFlag;
signals:
void changedThreadFlag(void);
void changedMessageStr(void);
void setThreadFlag(bool);
void setMessageStr(QString);
private slots:
void setStr(QString);
void setFlag(bool);
void socketError(QAbstractSocket::SocketError);
};
And its implementation is...
SocketThread::SocketThread() {
socket_session = NULL;
threadFlag = false;
message = "NULL";
connect(this, SIGNAL(setThreadFlag(bool)), this, SLOT(setFlag(bool)));
}
...
void SocketThread::setStr(QString str) {
message = str;
}
void SocketThread::setFlag(bool flag) {
threadFlag = flag;
}
void SocketThread::run() {
while(true) {
if(threadFlag) {
QThread::msleep(100);
qDebug() << message;
} else
break;
}
qDebug() << "loop ended";
}
And I have one form which has a button, and I put a clicked() slot of it like this...
void Form1::on_qpushButton__set_white_level_0_clicked() {
qDebug() <<"clicked()";
--how can I emit the signal of the one of socketthread from here??
}
Now, the mainwindow is like this:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow) {
QString addr_server = "223.194.32.106";
int port = 11000;
SocketThread* socket_session = new SocketThread();
socket_session->connectToServer(addr_server, port);
ui->setupUi(this);
Form1* form1;
form1 = new Form1();
ui->stackedWidget_mainwindow->addWidget(form1);
ui->stackedWidget_mainwindow->setCurrentWidget(form1);
socket_session->run();
...
I just simply want to emit the signal setThreadFlag of the socketthread from inside of QPushbutton_clicked() slot.
Once the socket_session->run() started, I need to change the threadFlag by clicking the button by emitting setThreadFlag() of one's from the running thread. And I just stuck in here.
Does it possible even?
Or am I doing this all wrong from the beginning?
As mentioned in this post:
"Emitting a signal" == "calling a function"
So all you really have to do is call the signal function, and all connected slots should be called.
This of course means that the Form1 object needs a pointer to the thread object, i.e. it needs a copy of socket_session. Then you can simply call the signal on the object
socket_session->setThreadFlag(your_flag);
Of course, if the Form1 have a copy of the socket_session pointer, it might as well call setFlag directly, if it was public.
I just simply want to emit the signal setThreadFlag of the socketthread from inside of QPushbutton_clicked() slot.
No signal is needed – just call the function.
void Form1::on_qpushButton__set_white_level_0_clicked() {
qDebug() <<"clicked()";
// --how can I emit the signal of the one of socketthread from here??
// E.g. this way:
socket_session->setThreadFlag(true);
}
To make this possible, another fix is needed:
socket_session is a local variable in OP's exposed code.
To make it "persistent", it has to become e.g. a member variable.
So, the constructor MainWindow::MainWindow() has to be changed:
// Nope: SocketThread* socket_session = new SocketThread();
// Instead:
socket_session = new SocketThread();
and SocketThread* socket_session; has to be added to member variables of class MainWindow.
To make it accessible in Form1, it has to be passed to Form1 as well.
This could be done e.g. by making it a member variable in Form1 also which is initialized with a constructor argument (or set from MainWindow afterwards).
(I must admit that I never have used the Qt UI builder QtDesigner but build all my UIs by C++ code exclusively.)
But, now, another fix is necessary:
volatile doesn't make a variable suitable for interthread communication.
(This was used in ancient times before multi-threading started to be supported by C++11.)
However, this is wrong: Is volatile useful with threads?
An appropriate fix would be to use std::atomic instead:
// Wrong for interthread-com.
//volatile bool threadFlag;
// Correct:
std::atomic<bool> threadFlag; // #include <atomic> needed
FYI: SO: Multithreading program stuck in optimized mode but runs normally in -O0
And, finally, in SocketThread::SocketThread():
connect(this, SIGNAL(setThreadFlag(bool)), this, SLOT(setFlag(bool)));
is not necessary in this case.
SocketThread::setThreadFlag() could call SocketThread::setFlag() directly, or even write threadFlag itself:
void setThreadFlag(bool flag) { threadFlag = flag; }
As I (recommended to) make threadFlag atomic, it can be accessed from any thread without causing a data race.
Update:
After OP has updated the question:
I just simply want to emit the signal setThreadFlag of the socketthread from inside of QPushbutton_clicked() slot.
The button (created from UI Form1) can be connected in the MainWindow as well (without using any method of Form1):
QObject::connect(form1->button1, &QPushButton::clicked,
socket_session, &SocketThread::setThreadFlag,
Qt::QueuedConnection);
Notes:
About form1->button1, I'm not quite sure.
I noticed that widgets in UI generated forms can be accessed this way but I don't know the exact details (as I never used the Qt UI builder on my own).
I used the Qt5 style of QObject::connect().
This is what I would recommend in any case.
The Qt5 style is verified at compile time. –
Wrong connections are detected by the C++ type checking.
Additionally, any function with matching signature can be used – no explicit exposure of slots is anymore necessary.
Even conversion of non-matching signature or adding additional parameters becomes possible by using C++ lambdas which are supported as well.
Qt: Differences between String-Based and Functor-Based Connections
It is possible to connect signals and slots of distinct threads.
I used Qt::QueuedConnection to remark this as interthread communication.
(However, I roughly remember that Qt might be able to detect it itself.
See the doc. for Qt::AutoConnection which is the default.
Further reading: Qt: Signals & Slots
Btw. using the Qt signals for inter-thread communication would exclude the necissity to make SocketThread::threadFlag() atomic. It could become a simple plain bool threadFlag; instead. The slot SocketThread::setThreadFlag() is called in the Qt event loop of QThread, in this case.

Qt Application Random Crashes via using callbacks and emitting signals from std::thread or boost::thread

I have an annoying issue with Qt and multi threading. Below I have created some simplified code. In my real code, the principle is exactlty the same but way too complex hence for using a simplified version.
The problem is that the application randomly crashes during different points at the run-time with different messages:
free(): invalid pointer
double free or corruption
The crash is triggered from within Qt, I will explain at the end of the post.
Here is how the code works.
So, I have classA that starts a thread:
class classA
{
public:
void start();
boost::function<void (std::string)> __ptr; // for callback
private:
boost::thread * thread;
void run();
};
void classA:start()
{
thread = new boost::thread(&classA::run, this); // start the thread
}
and here is the actual method that runs in the separate thread:
void classA::run()
{
for (int i = 0; i < 50000; i++)
{
static int count = 0;
__ptr("test123" + std::to_string(++count));
}
}
In my QDialog inherited class, I have a simple method that assigns the boot::function so I have declared another boost::function ptr. The problem is not with the ptr, it is with Qt, read on, the call back works just fine...
class myClassB : public QDialog
{
Q_OBJECT
public:
explicit myClassB (QWidget *parent);
classA ca;
private:
boost::function<void (std::string)> __ptr;
void mycallback(std::string);
};
In the constructor of myClassB, I am assigning my call back to boost::function like this (like I said, the callback works fine).
myClassB::myClassB()
{
this->__ptr = ( boost::bind( &myClassB::mycallback, this, _1 ) );
ca.__ptr = __ptr;
}
Here is where the problem starts. In my callback within my classB QDialog, I emit a Qt signal
void myClassB::mycallback(std::string txt)
{
emit sig_qt_data_received(txt);
}
This signal gets connected in my classB's constructor:
connect(this, SIGNAL(sig_qt_data_received(std::string)), this, SLOT(data_received(std::string)), Qt::DirectConnection);
and finally, the implementation of the Qt slot:
void myclassB::data_received(std::string txt)
{
ui->lbl_status->setText(txt);
}
This is where the problem is:
If you remove ui->lbl_status->setText(txt);, the program works flawlessly, it never crashes, if you leave it, it randomly crashes:
free(): invalid pointer
double free or corruption
It appears that the problem is within Qt as when I remove the setText() references, it does not crash and I have followed just about every GUI multi-threading procedure I have found and I don't know what I am doing wrong.
To connect the Qt signal, I am using Qt::DirectConnection and if I use Qt::AutoConnection it will work without a crash but sometimes the whole UI freezes (Edit: this is incorrect, see my answer).
I hope someone can help. If you need more code / real code, let me know, I will write an actual runnable code that you can run and compile but the fundamentals are the same, that's how the code works.
I don't want to be using QThread.
Resolved! Qt::DirectConnection was the culprit, now I use Qt::AutoConnection and it never crashes and according to the docs it is the default:
(Default) If the receiver lives in the thread that emits the signal,
Qt::DirectConnection is used. Otherwise, Qt::QueuedConnection is used.
The connection type is determined when the signal is emitted.
G.M's response above gave me the hint (Thanks):
the fact that explicitly specifying the connection type as
Qt::DirectConnection changes the behaviour suggests you've almost
certainly got a race condition due to threading
Also thank you jpo38 for suggesting / replying anyway.
Now I know I said sometimes it would freeze but no, that's incorrect, it never freezes, I had confused things.

QTimer::SingleShot fired after object is deleted

// Example class
class A : public QObject
{
Q_OBJECT
void fun() {
Timer::SingleShot(10, timerSlot); //rough code
}
public slot:
void timerSlot();
}
auto a = SharedPointer<A>(new A);
a->fun();
a->reset(); // a deleted
In this case after a is deleted and timer is fired, would it execute timerSlot()? I'm getting an extremely rare crash and not sure if it's because of something fishy in this logic.
Even if the timer fires, it won't trigger the slot. The docs of ~QObject state: All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. The only way you can trigger the A::timerSlot and delete A at the same time is if you use threads.
You are not obligated to disconnect an object's signals and slots before deleting it.
The QObject destructor will clean up obsolete signal-slot connection for you, as long as you:
Inherit from QObject
Use the Q_OBJECT macro in your class definition
Following these conventions ensures that your object emits a destroyed() signal when deleted. That's actually what Qt's signals-and-slots system uses to clean up dangling references.
You can listen to the destroyed() signal yourself if you'd like to add some debugging code to track object lifecycles.
(Depending on the particular version of Qt/moc you are using, it's quite possible that code with a non-QObject using slots, or a QObject-derived class that doesn't have Q_OBJECT in its header will still compile but cause the timerSlot() method to be invoked on a garbage pointer at runtime.)
I'm getting a extremely rare crash due to timer out of object scope which I need to fire just once. I use QTimer::singleShot which is static method and does not pertain to an instance of QTimer object which I would release with the context it fires the signal to.
That is of course solved in QTimer class and desired behavior controlled by the instance of timer class with non-static QTimer::singleShot property set to true.
// declaration
QScopedPointer<QTimer> m_timer;
protected slots:
void onTimeout();
// usage
m_timer.reset(new QTimer);
m_timer->setSingleShot(true);
QObject::connect(m_timer.data(), SIGNAL(timeout()), this, SLOT(onTimeout()));
m_timer->start(requiredTimeout);
So, no crash should happen due to timer released with the context object.
Edit: This answer was in response to the original question which did not use QObject but had class A as a standalone class inheriting nothing. The question was later edited making this answer obsolete, but I'll leave it here to show what would be needed if not using QObject.
The only way you can do that is if you keep the object alive until the timer has fired. For example:
class A : enable_shared_from_this<A> {
void fun() {
QTimer::singleShot(10, bind(&A::timerSlot, shared_from_this()));
}
public:
void timerSlot();
}
auto a = SharedPointer<A>(new A);
a->fun();
a->reset(); // a goes out of scope, but its referent is kept alive by the `QTimer`.
The reason the above works is that you capture a shared_ptr to class A when setting the timer, and the timer will hold onto it (else it can't fire).
If you don't like or can't use recent C++ features or Boost:
struct Functor {
Functor(SharedPointer<A> a) : _a(a) {}
void operator() { a->timerSlot(); }
SharedPointer _a;
};
class A {
void fun(shared_ptr<A> self) {
QTimer::singleShot(10, Functor(self));
}
public:
void timerSlot();
}
auto a = SharedPointer<A>(new A);
a->fun(a);
To reach certainty, you can stop the timer yourself:
class A : public QObject {
QTimer t;
A() { connect(Signal-Slots); }
~A() { t.stop(); }
fun() { t.start(10); }
...
};

Public member not initialized

I am making a client server application, with the server having a GUI. I am using Qt.
For communication I am using pipes.
I have divided the server application into a backend, and a GUI. The backend has a PipeServer class, and in the GUI, I have overriden functions like onReceiveMessage etc.
Everything worked fine until I decided to add a std::queue as a base class member.
At the start of the application, I get an exception, and upon inspection it seems that my queue does not start with 0 elements. In fact it seems like the queue is not initialized at all. There are 2 possibilites: it could be because I the GUI class inherits 2 classes, and somehow the second base class, which is my PipeServer does not properly initialize its members, or it could be because the pipeServerGUI object is moved to a different thread by QT.
Any ideas on how I could solve this?
Relevant code:
class HookServer
{
PIPEINST Pipe[INSTANCES];
HANDLE hEvents[INSTANCES];
VOID DisconnectAndReconnect(DWORD);
BOOL ConnectToNewClient(HANDLE, LPOVERLAPPED);
VOID GetAnswerToRequest(LPPIPEINST);
public:
std::queue<std::string> messages;
int init(std::string pipename);
int run();
virtual void onNewConnection() {};
virtual void onReceiveMessage(std::string message) {};
};
class HookServerGUI : public QObject, public HookServer
{
Q_OBJECT
void onReceiveMessage(std::string message);
void onNewConnection();
public slots:
void doWork() {
init("\\\\.\\pipe\\hookpipe");
run();
}
signals:
void signalGUI(QString message);
};
//GUIServerCreation
QThread *thread = new QThread;
HookServerGUI* worker = new HookServerGUI;
QObject::connect(worker,SIGNAL(signalGUI(const QString&)),this,SLOT(processMessage(const QString&)));
worker->moveToThread(thread);
thread->start();
QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection);
EDIT:
The exception is a access violation exception. It happens in this part of code:
VOID HookServer::GetAnswerToRequest(LPPIPEINST pipe)
{
onReceiveMessage(pipe->chRequest);
if(!messages.empty())
{
std::string s = messages.front();
messages.pop();
strcpy(pipe->chReply,s.c_str());
pipe->cbToWrite = strlen(s.c_str()+1);
}
}
Since messages.empty() return some huge number, it tries to read the first object and somehow fails.
There is also no PipeServerGUI constructor.
EDIT2:
I solved part of this problem by placing parenthesis after new HookServerGUI();
The problem is that still the function does not work, and throws a access violation exception. It happens on the front() line. When checked in a debugger, the function does have 1 element, so it is not because it is empty. Any ideas?
EDIT3:
With the second run, unfortunately the queue.size() is still incorrect. Seems like a data race to me.
The problems are in the code that you don't show, and it's a classic case of a memory bug, it looks like. Some code somewhere is writing on memory it doesn't own. Probably you have a bug in the way you use winapi. You need to create a minimal, self-contained test case.
I think you might be shooting yourself in the foot by not using QLocalSocket: on Windows, it's a named pipe - exactly what you want.
Besides, this is C++ code. There is no reason at all to put either PIPEINST or HANDLE into a raw C array. Use QVector or std::vector. Probably the rest of the code is full of C-isms like that, and something somewhere goes wrong.
I wouldn't discount a buffer overrun, since obviously you are ignoring the size of the buffer in PIPEINST from the - the strcpy can overrun the buffer. I'm also not sure that PIPEINST from the example code is using the same character type as what std::string::c_str() is returning.
Even if you wanted to implement your code using explicit pipes without QLocalSocket, you should still use C++, QString etc. and understand what's going on with your data.

Application->Processmessages in QT?

In Borland 6 I often use this to unstuck program action:
Application->Processmessages();
Now, with QT 4.8.1, I don't have found in this foreign (for me) documentation of QT.
Can anyone help me?
In Qt, you'd use the static function QApplication::processEvents().
Alas, your issue is that the design of your code is broken. You should never need to call processEvents simply to "unstuck" things. All of your GUI code should consist of run-to-completion methods that take a short time (on the order of single milliseconds: ~0.001s). If something takes longer, you must split it up into smaller sections and return control to the event loop after processing each section.
Here's an example:
class Worker: public QObject
{
Q_OBJECT
int longWorkCounter;
QTimer workTimer;
public:
Worker() : ... longWorkCounter(0) ... {
connect(workTimer, SIGNAL(timeout()), SLOT(longWork());
}
public slots:
void startLongWork() {
if (! longWorkCounter) {
workTimer.start(0);
}
}
private slots:
void longWork() {
if (longWorkCounter++ < longWorkCount) {
// do a piece of work
} else {
longWorkCounter = 0;
workTimer.stop();
}
}
};
A zero-duration timer is one way of getting your code called each time the event queue is empty.
If you're calling third party blocking library code, then the only (unfortunate) fix is to put those operations into slots in a QObject, and move that QObject to a worker thread.