Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

c++ - QThreads , QObject and sleep function

The problem I encountered is that I decided to implement QThreads the way they are supposed to, based on numerous articles:
https://www.qt.io/blog/2010/06/17/youre-doing-it-wrong
http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/

and issue at hand is that since the algorithm is run in separate QObject (wrapped in QThread). How can I call out something like Thread::Sleep or smth .. Any ideas?

A small description of the software. Basically my application solves TSP (Traveling salesman problem). As the search goes along, it saves all the states in the history as frames ..(like visual frames). The search algorithms will be run on one thread. Main thread is handling with the GUI. Then there is the Mediaplayer like thread which tells Main thread what frame to display on screen. So where does the sleep come in ? In gui there is a slider that user can use to fast forward or go in normal pace.. that slider tells via signal slot to Mediaplayer thread to go faster or slower.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What we've done is basically something like this: (written by memory, as I don't have our code checked out on this computer)

class Sleeper : public QThread {
public:
   void sleep(int ms) { QThread::sleep(ms); }
};

void sleep(int ms);

// in a .cpp file:
static Sleeper slp;

void sleep(int ms) {
    slp.sleep(ms);
}

The key is that the QThread::sleep function causes the calling thread to sleep, not the threaf represented by the QThread instance. So just create a wrapper which calls it via a custom QThread subclass.

Unfortunately, QThread is a mess. The documentation tells you to use it incorrectly. A few blog posts, as you've found, tell you a better way to do it, but then you can't call functions like sleep, which should never have been a protected thread member in the first place.

And best of all, even no matter which way you use QThread, it's designed to emulate what's probably the worst thread API ever conceived of, the Java one. Compared to something sane, like boost::thread, or even better, std::thread, it's bloated, overcomplicated and needlessly hard to use and requiring a staggering amount of boilerplate code.

This is really one of the places where the Qt team blew it. Big time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...