are glib signals asynchronous? - asynchronous

When using glib to dispatch signals through emit, are all the "listeners"/handlers called back-to-back or is control relinquished to the event loop after each listener/handler?

The callbacks are all called back-to-back without relinquishing control to the main loop.
Actually, as far as I know, g_signal_emit() does not even return control until all handlers are called, so there is no opportunity for the main-loop to kick-in.
So to answer the question in the title of this post: no, glib signals are not asynchronous.

GLib signals can be handled synchronously or asynchronously. GObject signals are always synchronous, i.e. when you emit a signal it does not return until the signal is handled.
To have a signal asynchronously handled with GLib, (I am using vala for brevity - use the vala compiler to convert the code into plain C) you must define a signal Source, or use a predefined one, as for example IdleSource or TimeoutSource (when I/O is out of question). For example assume that you have a function
void my_func() {
stdout.puts("Hello world! (async)\n");
}
and you want to call it asynchronously (from the same thread!) from
void caller() {
// Here you want to insert the asynchronous call
// that will be invoked AFTER caller has returned.
// Body of caller follows:
stdout.puts("Hello world!\n");
}
Here is how you do it:
void caller() {
// Code for the asynchronous call:
var ev = new IdleSource();
ev.set_callback(() => {
my_func();
return Source.REMOVE; // Source.REMOVE = false
});
ev.attach(MainContext.default());
// Body of caller follows:
stdout.puts("Hello world!\n");
}
You will get the following output:
Hello world!
Hello world! (async)
The my_func() function will be executed when MainLoop is idle (i.e. it has no other signals to process). To trigger it after a specific time interval has elapsed use the TimeoutSource signal source. A MainLoop must be running, otherwise this will not work.
Documentation:
https://valadoc.org/glib-2.0/index.htm
https://developer.gnome.org/glib/stable/glib-The-Main-Event-Loop.html

Related

Should accept() be used only at the end of a slot?

I see the accept() somewhat similar to a return, so I've been putting it a the end of my slots with no code afterwards. That is, the accept() "finishes" the execution of the dialog.
Nevertheless, I came across the need to close a dialog and open a new one from a slot in the first one. Therefore, what I thought was moving the accept() to the beginning of the slot and initializing the second dialog after it. Something like the following:
void FirstDialog:slotFirstDialog()
{
accept();
// Setup second dialog arguments
// ...
SecondDialog *sd = new SecondDialog();
sd->exec();
}
Is this use of accept() valid? Is it good practice?
I'd avoid it. Calling accept() can trigger a delayed deletion of FirstDialog (say, if it has the Qt::WA_DeleteOnClose flag set)1; in that case, it would be deleted in one of the first events dispatched by the nested event loop (sd->exec()), which would lead to go on executing code in a method of an instance that has been deleted. This is just a sample problem on the top of my head, I'm sure others can be found.
I'd probably just hide the dialog before calling exec() on the other, and call accept() after the end of the nested event loop.
void FirstDialog:slotFirstDialog()
{
// Setup second dialog arguments
// ...
SecondDialog *sd = new SecondDialog();
hide();
sd->exec();
accept();
// NB are we leaking sd?
}
By the way:
SecondDialog *sd = new SecondDialog();
sd->exec();
here you are allocating on the heap a dialog without a parent, so either you set the Qt::WA_DeleteOnClose or explicitly call this->deleteLater() inside its code, or you are leaking the dialog instance.
Notes:
and it is explicitly remarked in the documentation
As with QWidget::close(), done() deletes the dialog if the Qt::WA_DeleteOnClose flag is set.
QDialog::accept calls QDialog::done with a dialog code Accepted. Here is how QDialog::done looks like:
void QDialog::done(int r)
{
Q_D(QDialog);
setResult(r);
hide();
d->close_helper(QWidgetPrivate::CloseNoEvent);
d->resetModalitySetByOpen();
emit finished(r);
if (r == Accepted)
emit accepted();
else if (r == Rejected)
emit rejected();
}
which, according to the documentation:
Hides the modal dialog and sets the result code to Accepted.
With this in mind, I think this is not a question of a good practice, but of what your application logic requires.

Qt event loop and unit testing?

I'we started experimenting with unit testing in Qt and would like to hear comments on a scenario that involves unit testing signals and slots.
Here is an example:
The code i would like to test is (m_socket is a pointer to QTcpSocket):
void CommunicationProtocol::connectToCamera()
{
m_socket->connectToHost(m_cameraIp,m_port);
}
Since that is an asynchronous call i can't test a returned value. I would however like to test if the response signal that the socket emits on a successful connection (void connected ()) is in fact emitted.
I've written the test below:
void CommunicationProtocolTest::testConnectToCammera()
{
QSignalSpy spy(communicationProtocol->m_socket, SIGNAL(connected()));
communicationProtocol->connectToCamera();
QTest::qWait(250);
QCOMPARE(spy.count(), 1);
}
My motivation was, if the response doesn't happen in 250ms, something is wrong.
However, the signal is never caught, and I can't say for sure if it's even emitted. But I've noticed that I'm not starting the event loop anywhere in the test project. In the development project, the event loop is started in main with QCoreApplication::exec().
To sum it up, when unit testing a class that depends on signals and slots, where should the
QCoreApplication a(argc, argv);
return a.exec();
be run in the test environment?
I realize this is an old thread but as I hit it and as others will, there is no answer and the answer by peter and other comments still miss the point of using QSignalSpy.
To answer you original question about "where the QCoreApplication exec function is needed", basically the answer is, it isn't. QTest and QSignalSpy already has that built in.
What you really need to do in your test case is "run" the existing event loop.
Assuming you are using Qt 5:
http://doc.qt.io/qt-5/qsignalspy.html#wait
So to modify your example to use the wait function:
void CommunicationProtocolTest::testConnectToCammera()
{
QSignalSpy spy(communicationProtocol->m_socket, SIGNAL(connected()));
communicationProtocol->connectToCamera();
// wait returns true if 1 or more signals was emitted
QCOMPARE(spy.wait(250), true);
// You can be pedantic here and double check if you want
QCOMPARE(spy.count(), 1);
}
That should give you the desired behaviour without having to create another event loop.
Good question. Main issues I've hit are (1) needing to let app do app.exec() yet still close-at-end to not block automated builds and (2) needing to ensure pending events get processed before relying on the result of signal/slot calls.
For (1), you could try commenting out the app.exec() in main(). BUT then if someone has FooWidget.exec() in their class that you're testing, it's going to block/hang. Something like this is handy to force qApp to exit:
int main(int argc, char *argv[]) {
QApplication a( argc, argv );
//prevent hanging if QMenu.exec() got called
smersh().KillAppAfterTimeout(300);
::testing::InitGoogleTest(&argc, argv);
int iReturn = RUN_ALL_TESTS();
qDebug()<<"rcode:"<<iReturn;
smersh().KillAppAfterTimeout(1);
return a.exec();
}
struct smersh {
bool KillAppAfterTimeout(int secs=10) const;
};
bool smersh::KillAppAfterTimeout(int secs) const {
QScopedPointer<QTimer> timer(new QTimer);
timer->setSingleShot(true);
bool ok = timer->connect(timer.data(),SIGNAL(timeout()),qApp,SLOT(quit()),Qt::QueuedConnection);
timer->start(secs * 1000); // N seconds timeout
timer.take()->setParent(qApp);
return ok;
}
For (2), basically you have to coerce QApplication into finishing up the queued events if you're trying to verify things like QEvents from Mouse + Keyboard have expected outcome. This FlushEvents<>() method is helpful:
template <class T=void> struct FlushEvents {
FlushEvents() {
int n = 0;
while(++n<20 && qApp->hasPendingEvents() ) {
QApplication::sendPostedEvents();
QApplication::processEvents(QEventLoop::AllEvents);
YourThread::microsec_wait(100);
}
YourThread::microsec_wait(1*1000);
} };
Usage example below.
"dialog" is instance of MyDialog.
"baz" is instance of Baz.
"dialog" has a member of type Bar.
When a Bar selects a Baz, it emits a signal;
"dialog" is connected to the signal and we need to
make sure the associated slot has gotten the message.
void Bar::select(Baz* baz) {
if( baz->isValid() ) {
m_selected << baz;
emit SelectedBaz();//<- dialog has slot for this
} }
TEST(Dialog,BarBaz) { /*<code>*/
dialog->setGeometry(1,320,400,300);
dialog->repaint();
FlushEvents<>(); // see it on screen (for debugging)
//set state of dialog that has a stacked widget
dialog->setCurrentPage(i);
qDebug()<<"on page: "
<<i; // (we don't see it yet)
FlushEvents<>(); // Now dialog is drawn on page i
dialog->GetBar()->select(baz);
FlushEvents<>(); // *** without this, the next test
// can fail sporadically.
EXPECT_TRUE( dialog->getSelected_Baz_instances()
.contains(baz) );
/*<code>*/
}
I had a similar issue with Qt::QueuedConnection (event is queued automatically if the sender and the receiver belongs to different threads). Without a proper event loop in that situation, the internal state of objects depending on event processing will not be updated. To start an event loop when running QTest, change the macro QTEST_APPLESS_MAIN at the bottom of the file to QTEST_MAIN. Then, calling qApp->processEvents() will actually process events, or you can start another event loop with QEventLoop.
QSignalSpy spy(&foo, SIGNAL(ready()));
connect(&foo, SIGNAL(ready()), &bar, SLOT(work()), Qt::QueuedConnection);
foo.emitReady();
QCOMPARE(spy.count(), 1); // QSignalSpy uses Qt::DirectConnection
QCOMPARE(bar.received, false); // bar did not receive the signal, but that is normal: there is no active event loop
qApp->processEvents(); // Manually trigger event processing ...
QCOMPARE(bar.received, true); // bar receives the signal only if QTEST_MAIN() is used

BackgroundWorker.RunWorkerCompleted event in WPF

There is a scenario in which a user terminates the application, while it is still processing data via BackgroundWorker.
I would like to send cancel or terminate command to this method. I tried calling CancelAsync() method, but it obviously didn't work the way I expected and the worker still continued processing.
What is a good way to signal the BackgroundWorker, and especially its RunWorkerCompleted method to stop processing?
Do I have to use state variables?
This is the code executed when you call CancelAsync() on a BackgroundWorker
public void CancelAsync()
{
if (!this.WorkerSupportsCancellation)
{
throw new InvalidOperationException(SR.GetString
("BackgroundWorker_WorkerDoesntSupportCancellation"));
}
this.cancellationPending = true;
}
As you can see, they set the internal cancellationPending variable to true after checking the value of WorkerSupportsCancellation.
So you need to set WorkerSupportsCancellation = true;, when you exit from your app call backGroundWorkerInstance.CancelAsync() and inside the DoWork or RunWorkerCompleted test the CancellationPending. If it's true stop your process.

Messaging using BeginReceive and EndReceive on ServiceBus does not work for me

I need asynchronous messaging on the bus.
This is the code I'm using:
//set callback to get the message
MessageReceiver messageReceiver = MessagingFactory.CreateMessageReceiver(BaseTopicName + "/subscriptions/" + addressee,
ReceiveMode.PeekLock);
IAsyncResult result = messageReceiver.BeginReceive(AsyncGet, messageReceiver);
Debug.WriteLine("After BeginReceive");
// Wait for the WaitHandle to become signaled.
Thread.Sleep(0);
result.AsyncWaitHandle.WaitOne();
// Close the wait handle.
result.AsyncWaitHandle.Close();
//return the information
Debug.WriteLine("return the information");
Here is the AsyncGet:
public void AsyncGet(IAsyncResult result)
{
Debug.WriteLine("Start AsyncGet");
MessageReceiver messageReceiver = result.AsyncState as MessageReceiver;
BrokeredMessage = messageReceiver.EndReceive(result);
Debug.WriteLine("Finish AsyncGet");
messageReceiver.Close();
}
The output I get is:
After BeginReceive
return the information
Start AsyncGet
Finish AsyncGet
It says that the line result.AsyncWaitHandle.WaitOne(); did not stop execution until the thread of AsyncGet finishes, as I thought it should.
Please,tell me what I'm doing wrong here.
Thanks!
I just double-checked the source code. This is by design.
The wait handle on the IAsyncResult gets triggered as the operation completes and before the callback gets invoked. The callback and the wait handle on the async result are two alternate methods to wait for completion of the operation. To achieve what you want to do here - blocking your thread based on completion of the operation and get the response through the callback - you'd need to have an explicit wait handle (ManualResetEvent) in your app and Set() that to signaled as the callback fires.

Whould the function be garbage collected before evaluating?

I have that function in the class:
private function fireItemCreated(data: ByteArray): void {
setTimeout(function(): void {
var event: ItemCreatedEvent = new ItemCreatedEvent(data);
dispatchEvent(event);
}, 1000);
}
This function called to dispatch item created event when image thumbnail created.
But it delays event on some time to prevent user interface freezes. And I'm guessing what could be happen if garbage collector executes after fireItemCreated function call but before timer event. Does the closure will be removed or it stays until it will be executed?
It can't happen.
If the function is called then setTimeout is called. The function-object passed to setTimeout creates a strong closure-binding with the linked execution context and all setTimeout callback functions are protected (strongly held) by the host engine (imagine there is an invisible var timeouts = [] you can't access). It wouldn't be fun if timers were magically swallowed up by the evil Grime Captain.
Good question and Happy coding.
The issue described can actually happen in some other languages and their implementations of Timers. See .NET's Threading.Timer Class and the notes.

Resources