Threads inside a qt class


I have this class inside a qt application that has some data defined:

class TableView:public QWidget { Q_OBJECT public:TableView (QWidget * parent = 0); std::vector < float > arr;

and some class functions and so on.. Now I want to add a socket server in another thread (posibly from inside this class) that is able to access data from this class when it recives something from the socket, calculate new data and return.

For the test I used:

//defines DWORD WINAPI SocketHandler(void* lp); DWORD WINAPI starttremeshserver(void* lp); CreateThread(0,0,&starttremeshserver, (void*)csock , 0,0);

This works. Now I need something easy and platform independent. Maybe something with qthread since I am working in qt.

So the question is, can I make a new thread function inside a class that can access class data. ty


Qt provides everything you need. Your needs are as follows:


Thread-safe (serialized) access to the data members of the TableView class.

</li> <li>

Networking primitives.

</li> <li>

Flexibility to move network access to a separate thread.

</li> </ol>

You are probably receiving data from the network, and want to update the arr member. You'd do it like so:


Create a QObject-derived class, say Processor, that has a slot that sets up the network connection (probably a QTcpServer). Upon a connection, use QTcpSocket to exchange data. Make sure all your data handling is done in slots in the class. When you have new values to update in the vector, simply emit some signal, like hasFloat(int,float).

</li> <li>

Add a setFloat(int,float) slot in the TableView.

</li> <li>

Connect the setFloat signal from the instance of Processor to your TableView.

</li> </ol>

At this point, everything runs in the GUI thread, but the code is non-blocking since you never wait for network data; you respond to the signals emitted by QTcpServer and QTcpSocket. You can leave it like that if you wish.

Having the Processor class run in a separate thread, if your benchmarking shows that your main thread is CPU bound, is then trivial:

int main(int argc, char** argv) { bool separateThread = true; QApplication app(argc, argv); TableView view; Processor proc; connect(&proc, SIGNAL(hasFloat(int,float)), &view, SLOT(setFloat(int,float))); QThread thread; if (separateThread) { thread.start(); proc.moveToThread(&thread); } view.show(); const bool rc = app.exec(); if (thread.isRunning()) { thread.exit(); // tells the event loop in the thread to bail out thread.wait(); // waits for the above to finish } return rc; }

There's this misconception that spreading things across threads somehow magically makes them better. Threads are a solution to a particular problem: CPU-boundedness of the computations being done, and blocking APIs. If your processing is trivial, you are not likely to be CPU bound. Qt provides nonblocking, asynchronous networking. Thus, usually, spinning a second thread is entirely unnecessary.

You must show real numbers first to show you otherwise. Else you're buying into the <em>cargo cult of threading</em>: oh, it's networking, it must go into a separate thread. Nope, not necessarily. Measure first. Understand what you're doing.

The reason for thread safety in the above code is as follows: when you move the Processor instance to a different thread, Qt will reconnect all signal-slot connections using Qt::QueuedConnection type. Thus, when Processor emits hasFloat, it will internally cause an event to be queued in the event queue of the thread where TableView lives -- the GUI thread, in this case. When the event loop spins (here it'd be the application's event loop) -- it'll pick up the event and execute a call to TableView::setFloat. This ensures that the access to the arr data member is serialized and there are is no possibility of concurrent access from multiple threads.


I'd personally look for more high level socket support, something based on boost perhaps, anyway for threads you can use <thread> in C++11.

To answer your specific question:

class Foo { private: void spinthread() { thread t([this] { this->bar = 12; }); } private: int bar; }

If you're using Win32 threads API, the thread proc has a parameter which you can use to pass your instance to during the CreateThread call.


Qt has threading support as can be found <a href="http://qt-project.org/doc/qt-5.0/threads.html" rel="nofollow">here</a>.

In addition to threads and accessing the data, you'll need synchronization for thread-safe code. This is called pthread mutex in linux, and in Qt its called QMutex as mentioned <a href="http://qt-project.org/doc/qt-5.0/threads-synchronizing.html" rel="nofollow">here</a>.

You can find the Qt networking primitives <a href="http://doc.qt.nokia.com/4.7-snapshot/network-programming.html" rel="nofollow">here</a>.

Using the Qt implementation of these threading and networking primitives will be portable, so should work for you on windows.

Regarding your question about creating a thread function from a class that accesses data on that class, the answer is yes. Instead of creating a thread function, it would be better to create a thread object, namely a QThread. When you create the thread object, you'll need to pass a reference to the instance of said class, which will allow the thread to access the class instance.


  • VBA copy from a union of two ranges to a row of another range
  • How can I replace the copied text from QTextEdit in my clipboard?
  • How to prevent Console Application from terminating when pressing “Ctrl+C” in C?
  • Wait for a SLOT to finish the execution with Qt
  • How to (re)name an empty column header in a pandas dataframe without exporting to csv
  • Is the content element used in Polymer 1.0?
  • Qt: closing modal dialog closes the program
  • Matrix as Applicative functor, which is not Monad
  • Segmentation Fault 11 on upgrading to Swift 2.0
  • gulp: passing dependent task return stream as parameter
  • Is it possible to use material-ui button navigation with react-router?
  • How many Flip Flops will this code produce?
  • Int to char conversion rule in C when int is outside the range of char
  • Qt — pass events to multiple objects?
  • R ggvis interactive slider for calculating y values (e.g. for background correction)
  • RFX equivalent data type for _int64 in Informix
  • Error: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
  • Camel REST Bean Chaining
  • How to merge two tables and transpose rows to columns
  • Upgrade to g++ 4.7 (with c++11 support): any ABI incompatibility?
  • Handling exceptions in a class library enveloping a device driver
  • Is MVC2 ASP.Net URLDecoding automatically?
  • qt how to know that a pushbutton is clicked?
  • Full 8 bit adder, illogical output
  • How to send control C to Mac Terminal using python?
  • How to initialize context? [closed]
  • Granting permissions to Azure Active Directory Web Application automatically
  • back button function for phonegap windows phone 7
  • triggering user space with kernel
  • In matplotlib, how do you change the fontsize of a single figure?
  • Unexpected token ILLEGAL while running node.js mocha test
  • Intel-64 and ia32 atomic operations acquire-release semantics and GCC 5+
  • Entity Framework Code First TPC Inheritance Self-Referencing Child Class
  • Check for zero lines output from command over SSH
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • Force show.bind execution
  • MailKit: The IMAP server replied to the 'EXAMINE' command with a 'BAD' response
  • Control modification in presentation layer
  • Is there a amazon webstore API for customers?
  • Display Images one by one with next and previous functionality