QThread always stuck in wait - qt5

I am trying to use QThread to call a function in another thread without having the UI to freeze. I am using QT5.11.2 on both windows and linux.
Everything works fine on windows but the wait() function for QThread never returns no matter what.
I use RHEL7 on linux
Here is what I am doing:
void MainWidget::configure_click(double value)
{
QThread *myThread = QThread::create([this, value]{ Configure(value); });
dsoThread->setObjectName("My Configure Thread");
QObject::connect(myThread, &QThread::finished, [](){ qDebug()<< "Configure Thread has finished";}); // This is never printed
myThread->start();
myThread->wait(); // Never returns from this
myThread->quit();
myThread->deleteLater();
}
My Configure function prints its start and finish and both lines are being printed on run time
void MainWidget::Configure(double value)
{
qDebug() << QThread::currentThread() << " started";
// Code to execute
qDebug() << QThread::currentThread() << " finished";
}
I even read that quit() forces the thread to stop, so just for testing I tried switching quit() and wait() like so
myThread->quit();
myThread->wait(); // Never returns from this either
myThread->deleteLater();
I even tried looping the isRunning() function instead of wait() but I got the same results
while(myThread->isRunning()) // Same goes for !isFinished()
{
// Do nothing
}
It seems like no matter what the thread never knows that it was finished.
What can I do to either solve this problem or to check why this is happening?

You haven't start()ed the thread.
myThread->wait(); in gui thread waits for thread to terminate so it blocks gui thread event loop, so you lose all benifints of threading this way and might as well just do Configure(value); without threading.
Documentation says:
wait() and the sleep() functions should be unnecessary in
general, since Qt is an event-driven framework. Instead of
wait(), consider listening for the finished() signal. Instead of
the sleep() functions, consider using QTimer.

Related

How to force a libusb event so that libusb_handle_events() returns

Suppose I have a libusb program that just uses the hotplug API. You register a callback and then apparently have to call libusb_handle_events() in a loop which then calls your hotplug callback.
int LIBUSB_CALL hotplugCallback(libusb_context* ctx,
libusb_device* device,
libusb_hotplug_event event,
void* user_data)
{
cout << "Device plugged in or unplugged";
}
void main()
{
libusb_init(nullptr);
libusb_hotplug_register_callback(nullptr,
static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
LIBUSB_HOTPLUG_NO_FLAGS,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
&hotplugCallback,
this,
&hotplugCallbackHandle);
for (;;)
{
if (libusb_handle_events_completed(nullptr, nullptr) != LIBUSB_SUCCESS)
return 1;
}
return 0;
}
The question is, without timeout hacks how can I exit this event loop cleanly? I can't find any functions that force libusb_handle_events() (or libusb_handle_events_completed()) to return. In theory they could just never return.
Sorry if this is late.
The question could have been phrased better but I'm assuming (from your comment updates) that your actual program resembles something a little closer to this:
int LIBUSB_CALL hotplugCallback(libusb_context *ctx,
libusb_device *device,
libusb_hotplug_event event,
void *user_data) {
cout << "Device plugged in or unplugged";
}
void SomeClass::someFunction() {
libusb_init(nullptr);
libusb_hotplug_register_callback(nullptr,
static_cast<libusb_hotplug_event>(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
LIBUSB_HOTPLUG_NO_FLAGS,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
LIBUSB_HOTPLUG_MATCH_ANY,
&hotplugCallback,
this,
&hotplugCallbackHandle);
this->thread = std::thread([this]() {
while (this->handlingEvents) {
int error = libusb_handle_events_completed(context, nullptr);
}
});
}
Let's say your object is being deallocated and, no matter what is happening on the USB bus, you don't care and you want to clean up your thread.
You negate this->handlingEvents and you call thread.join() and the thread hangs for 60 seconds and then execution resumes.
This is done because the default behavior of libusb_handle_events_completed calls libusb_handle_events_timeout_completed and passes in a 60 second timeout interval with plans to make it infinite.
The way you force libusb_handle_events_completed to return is you call libusb_hotplug_deregister_callback which wakes up libusb_handle_events(), causing the function to return.
There is more info about this behavior in the docs.
So your destructor (or wherever you want to stop listening immediately) for the class could look something like this:
SomeClass::~SomeClass() {
this->handlingEvents = false;
libusb_hotplug_deregister_callback(context, hotplugCallbackHandle);
if (this->thread.joinable()) this->thread.join();
libusb_exit(this->context);
}
In the function:
int libusb_handle_events_completed(libusb_context* ctx, int* completed)
You can change the value of the completed to "1" so the function will return without blocking
According to their docs:
If the parameter completed is not NULL then after obtaining the event
handling lock this function will return immediately if the integer
pointed to is not 0. This allows for race free waiting for the
completion of a specific transfer.
There is no functions in libusb that force libusb_handle_events() to return.
It's recommended to use libusb_handle_events() in a dedicated thread so your main thread will not be blocked by this call. Even though, if you need to manipulate the call of the event handler you can put the call in a while(condition) and change the condition state in your main thread.
Libusb documentation details this here.

Why is any code executed before this has finished?

Supposing I have a code like this:
[ApiConnection getServerTimeWithBlock:^(BOOL gotTimeResponse){
if(gotTimeResponse)
{
//we're online, got the response from time endpoint
[ApiConnection registerNewCustomerWithBlock:^(NSString* val){
if(val)
{
NSLog(#"val: %#",val);
}
else
{
NSLog(#"no val");
}
}];
}
else
{
//we're offline
}
}];
NSLog(#"TEST");
why is the last NSLog executed before the whole first block has finished execution?
Because the getServerTimeWithBlock: method is asynchronous, so it returns immediately and runs on a background thread. When that thread is complete is calls the completion block.
So, the method runs before your log, but the completion block (usually) doesn't (it might if there was an error or something like that).
Presumably getServerTimeWithBlock: is exectuted asynchronously. When supplying the block, you're telling the APIConnection object what to do when it has finished getting the server time. This will involve network fetches and reading data back, which you don't want to wait for on the main thread as this will cause your UI to freeze. Your program therefore carries on, and the block is executed whenever the fetch is complete.
Note that blocks do not imply that asynchronous or multithreaded code is in use (see NSArray's enumerateWithBlock: method, for example) but it seems very likely to be the case here.

Having a winforms app wait for a few minutes before proceeding

I've seen a few references on Stack Overflow about using the Timer Class to do what I want but I'm not convinced it's the right solution to the problem.
Basically, I have a button (in .NET 4.0) that when clicked will go through a few different subroutines and do certain things:
Restart some services
Launch a command line application that finishes automatically
Launch a second command line application that finishes automatically
Launch a third command line application that finishes automatically
The problem I have right now is that the program just goes through each thing and fires it off as quickly as possible - not a problem except that the third command line application must only fire after the first three are completed.
I had a sleep call in the code, except that this froze the UI and I have a status bar on this application that I wanted to have update to let the user know things are occurring.
I was thinking about a Timer object but I'm not sure that would actually cause there to be a pause before doing the next thing.
I'm using a Process.Start method to fire off the command line applications, so it doesn't actually raise an event. Should I just have my subroutine raise an event and then have the third Process.Start method wait for that event to fire before it goes?
This small snippet might help you. Try to get the idea and implement your own code.
try
{
Process myProcess;
myProcess = Process.Start("Notepad.exe");
while (true)
{
if (!myProcess.HasExited)
{
// Discard cached information about the process.
myProcess.Refresh();
// Print working set to console.
Console.WriteLine("Physical Memory Usage: "
+ myProcess.WorkingSet.ToString());
// Wait 2 seconds.
Thread.Sleep(2000);
}
else {
break;
}
}
// Close process by sending a close message to its main window.
myProcess.CloseMainWindow();
// Free resources associated with process.
myProcess.Close();
}
catch(Exception e)
{
Console.WriteLine("The following exception was raised: ");
Console.WriteLine(e.Message);
}

What are my errors using libevent timout events?

I am trying to learn libevent for use in a future project. I am attempting to create a event that calls it's call back function each time it times out. All the call back function does is print "timeout_cb called" to standard out.
my code for the call back function is:
static void timeout_cb(evutil_socket_t fd, short what, void *arg) {
printf("timeout_cb called");
}
my code for the event is:
struct event *toEvent; // time out event do this every so often
toEvent = event_new(base, -1, EV_TIMEOUT, timeout_cb, NULL); // base is the event base
event_add(toEvent, &five_seconds); //five_seconds is a timeval struct with 5 seconds
The program will compile and run with no errors or warnings but it doesn't print out the phrase in the call back function. I have used similar printf statements in other callback types to verify they were called and that various lines were reached inside the functions, but this does nothing. I waited 30 seconds or so but still nothing printed to the screen. What am I doing wrong the with the pure timeout event.
You'll have to do
event_new(base, -1, 0, timeout_cb, NULL);
Note that there's some convenience macros to add timers, evtimer_new(), evtimer_add(), see the docs

How to wake up a process blocked by pause()?

I need to block and wake a process using SIGUSR2 and SIGUSR1 respectively. Below here's my signal handler sub routine. How do I wake a process blocked by pause?
void sig_handler(int sig) {
static int i = 1;
if(sig == SIGUSR2) {
pause();
}
else if(sig == SIGUSR1) {
/* I don't what to write here */
}
}
Also, I read somewhere pause() is not a good programming practice, is there any other means to suspend a process for some time?
See this page
In general, doing a lot of works in signals is ... tricky. Some things are not async-signal-safe, and therefore it makes robust programming there a bit difficult. In your case, pause() waits for a signal to arrive, but since you are calling it from the signal handler, it is not going to work there (I think).
As to making the process sleep and resume on signals. Look at the page I linked above. The best way is to have the signal handlers simply set flags and have the main thread (i.e. in main() or in an event loop) react to these flags. As recommended by the page, use sigsuspend when SIGUSR2 is received to pause the process until SIGURS1 is received.
It's simple. Use the 'kill' system call-
void sig_handler(int sig) {
static int i = 1;
if(sig == SIGUSR2) {
pause();
}
else if(sig == SIGUSR1) {
kill(<pid of process to wake up>, sig);
// make sure that process with pid has registered for sig
}
}