开发者

Does QThread::sleep() require the event loop to be running?

I have a simple client-server program written in Qt, where processes communicate using MPI. The basic design I'm trying to implement is the following:

  1. The first process (the "server") launches a GUI (derived from QMainWindow), which listens for messages from the clients (using repeat fire QTimers and asynchronous MPI receive calls), updates the GUI depending on what messages it receives, and sends a reply to every message.

  2. Every other process (the "clients") runs in an infinite loop, and all they are intended to do is send a message to the server process, receive the reply, go to sleep for a while, then wake up and repeat. Every process instantiates a single object derived from QThread, and calls its start() method. The run() method of these classes all look like this:

from foo.cpp:

void Foo::run()
{
  开发者_StackOverflow中文版  while (true)
    {
        // Send message to the first process
        // Wait for a reply
        // Do uninteresting stuff with the reply
        sleep(3);    // also tried QThread::sleep(3)
    }
}

In the client's code, there is no call to exec() anywhere, so no event loop should start.

The problem is that the clients never wake up from sleeping (if I surround the sleep() call with two writes to a log file, only the first one is executed, control never reaches the second). Is this because I didn't start the event loop? And if so, what is the simplest way to achieve the desired functionality?


Some classes in client code may need an event loop to be started. Why to use QThreads for clients if you don't have an event loop for the clients and you already using MPI?


A one liner answer to the question is - sleep and event loop are not related. Sleep makes the calling thread sleep irrespective of whether it's being called from thread's overridden run() function or any other function for that matter. It makes no difference and there is no escape. In fact, if exec() is called somewhere in run() (which the QThread's default implementation is) the control will not return to the caller.

The reason for the second log statement not getting written cannot be directly related with sleep() if the logger object is local or available to the run() function all the time. The control has to return to thread after designated amount of sleep is done. But meanwhile, the thread could lose control to transient objects like incoming connection.

Perhaps when this question was asked QThread::sleep() was a private function. Now with Qt 5, sleep or msleep or even usleep are public static functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜