Return to site

Qt Signal Slot Cross Thread

broken image


Create cross platform UI application with Qt - QML and c. Integrating QML and CPP for data and controllers. Qt-QML- Layouts, positioning, Components, User Inputs, Animations, themes. Qt - Signal and slots, Event systems, Event filtering. Qt- Threads - working with signal and slots. Inherited and Move To Thread.

Qt Signal Slot Cross Thread
  • The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments. QtScript and QML would have hardly been possible without that ability.
  • As QAbstractItemView uses AutoConnections, the signals will be queued if they are in another thread. So, AFAIU, the model and view must be in the same thread if things are not to break. It's not impossible that a model would try to insert and remove rows in quick succession.
  • 8BiTs 매일 코딩 홈페이지. (Qt) Cross Thread Signal and Slots - 2 Get Code.
  • Qt documentation states that signals and slots can be direct, queued and auto. It also stated that if object that owns slot ‘lives' in a thread different from object that owns signal, emitting such signal will be like posting message – signal emit will return instantly and slot method will be called in target thread's event loop.

I am implementing a small project where I am extensively using QThreads and signals/slots (and basically Qt 5). I can say I have a fair idea about how signals/slots work along with QThreads. (I have gone through all important material on StackExchange as well as these links 'You are doing it wrong' and its update You were not doing so wrong. I have also gone through Most correct way to use QThread) I am convinced about my design that I will have to subclass QThread but also add slots to the subclass (which I know will run in separate threads.)

My calling thread (object on the thread) hosts such slots of at least three different classes along with its own utility functions. My question is: How the context switches between different slots and functions affined to a thread are handled? Will there be a context switch if one of the function has sleep or wait called (should be right?)? Secondly is there anything specific behaviour for QThreads?

If there is nothing specific to Qt or QThreads, still I would like to know about this behaviour in general. Thanks in advance.

I think that you're confused by the cooperative multitasking exhibited by typical event driven applications, with their run-to-completion event handlers. This is how WIN16, GEM and other such platforms appeared to multitask with no context switches at all.

I'll attempt to clear this confusion after exposing the necessary background to this story.

A context switch is a way to reuse an available core to run another thread when the current one has used up its timeslice or is sleeping. It is an optimization of sort, when you're short on cores. Yes, it is an implementation detail of the platform that your code runs on. It is not even a necessary one: you cannot tell if your platform context-switches or not just by looking at it (really, other then side channel attacks).

QThread is just a thin thread controller object. The controlled thread is a platform object and Qt does nothing to alter its behavior. The QThread::run behaves just like it would on a native platform thread, because that's where it runs.

The QThread::run method only spins (exec() in Qt parlance) an event loop (of course it won't do it anymore if your reimplementation doesn't).

An event loop waits for events to arrive in the queue, and then notifies the target QObjects of their reception.

The cross-thread (queued) signal-slot connections are implemented by leveraging events. Upon emission, the signal copies its arguments and posts them in a QMetaCallEvent to each queued-connected receiver object. Since these objects live in another thread, the event loop running in their thread will get woken up. It will then pick up the event and have it handled by the target object's event method. Specifically, QObject::event implementation knows how to deal with the QMetaCallEvent: it will execute the slot call.

Thus, queued slot calls are acting as event handlers, since they are invoked as an effect of QObject::event() being invoked by the event loop. Whenever a queued slot executes, the call stack looks as follows:

  • your slot method,
  • QObject::event()
  • ..
  • QEventLoop::exec()
  • QThread::run
  • platform-specific thread function.

So, how can events and event handlers give an impression of multiprocessing? That's because all event handlers are running to completion. They never sleep nor block, they simply execute the short actions they need to, and immediately return to the event loop.

This behavior will be broken as soon as your event handlers become blocking. Since slots called via queued connections (cross-thread) are effectively QMetaCallEvent handlers, if you block/sleep/wait in them, you're sleeping the entire thread. Suppose you call QThread::sleep in your slot. The call stack then is:

  • platform-specific implementation of sleep,
  • QThread::sleep(),
  • your slot,
  • ..
  • QThread::run().

At this point, the thread simply isn't runnable. If the platform so chooses, another thread might run on the same core, to make use of it, but that is the platform's optional optimization that you have little control over.

  1. How the context switches between different slots and functions affined to a thread are handled?

    There are none. Or, more specifically, as long as there are QMetaCallEvent events stored in the event queue for a given thread, and as long as that thread is runnable, it will simply keep executing the queued slot calls. On an otherwise idle multicore machine, you can keep a thead executing queued slot calls with no additional context switches.

    If your slot sleeps or waits, the entire thread sleeps or waits.

  2. Will there be a context switch if one of the function has sleep or wait called?

    Not necessarily so. You're presuming that the operating system's implementation of interruptible wait will preempt your thread. This might be the case, or it might not be the case. Whatever happens, of course, your thread is sleeping at that point and obviously nothing else happens within it while it is sleeping.

Copy text and placeholders, variables to the clipboard

c++,qt,clipboard

You're not using the function setText correctly. The canonical prototype is text(QString & subtype, Mode mode = Clipboard) const from the documentation. What you want to do is assemble your QString ahead of time and then use that to populate the clipboard. QString message = QString('Just a test text. And..

Any way to catch an exception occurring on a thread I don't own?

c#,multithreading,exception

The thing worrying me most in the described case is abnormal thread termination inside that 3rd-party lib. Once a thread is throwing, you can't catch the exception via correct way because you're not the owner of that thread invocation (and it has no idea it should propagate the exception to..

How to pass QString variable to QFile?

qt,qstring,qfile

QString selected = model2->filePath(index); does not set the variable in the (maybe same named) member OptionsDialog::selected. This creates a new local variable. If you have a member variable called selected then you should use it like this: void OptionsDialog::getData(const QModelIndex &index) { selected = model2->filePath(index); .. } ..

Does wait() need synchronization on local variable

java,multithreading,synchronization

I don't know Android development tools, but the warning sounds over-zealous. The compiler is trying to help you to avoid synchronizing on an instance that is only visible to a single thread. It's smart enough to know that the local variable, r, can only be seen by one thread, but..

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of..

How can I have an animated system tray icon in PyQt4?

python,qt,pyqt,pyqt4,system-tray Ok google give me free slot machines without.

Maybe something like this. Create QMovie instance to be used by AnimatedSystemTrayIcon. Connect to the frameChanged signal of the movie and call setIcon on the QSystemTrayIcon. You need to convert the pixmap returned by QMovie.currentPixmap to a QIcon to pass to setIcon. Disclaimer, only tested on Linux. import sys from..

Looking to pause a thread using thread.sleep

java,multithreading

You're probably running into a race condition between the two threads, the fact that i isn't volatile also suggests that the threads may not be working with the same actual value as each other. Threads are also non-reentrant, meaning that once the run method exists, they can not be restarted..

Java 5 Multi threading, catch thread exceptions

java,multithreading,exception,concurrency,java-5

The most common approach is to submit a Callable to an Executor, and receive a Future. You can then call Future.get to find out if any exceptions were thrown. As for UncaughtExceptionHandler, you can only really use it with raw threads because Executors handle uncaught exceptions internally (thus you don't..

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

c++,multithreading,sorting,recursion

You problem originates in this line: int newArray[maxCount + 1]; You are trying to allocate ~250000 ints on the stack (on most 32 bit platforms it will take ~1MB of memory). Your thread's stack may not be able to do this. By the way, you should not do this -..

change QDir::rootPath() to program running path?

c++,qt

QCoreApplication::applicationDirPath() returns the exact directory path of your app, for example H:/programs if your app path is H:/programs/ftpserver.exe so if you modify that QString you can get the root dir. For example: QString rootPath = QCoreApplication::applicationDirPath(); rootPath.chop(rootPath.length() - 3); //we leave the 3 first characters of the path, the root..

How to differentiate a QNetworkReply is aborted or not?

c++,qt,networking

If aborted, QNetworkReply::error() should return QNetworkReply::OperationCanceledError, which means: the operation was canceled via calls to abort() or close() before it was finished. ..

Is there standard implementation for thread block/resume in java SE?

java,multithreading,wait

have a a look at the classes in java.util.conucurrent .. CountDownLatch might be a solution for your problem if i understand your problem correctly.

Multiple Threads searching on same folder at same time

c#,multithreading,file-search

Instead of using ordinary foreach statement in doing your search, you should use parallel linq. Parallel linq combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library. This will shield you from low level thread manipulation and..

What does QHeaderView::paintSection do such that all I do to the painter before or after is ignored

c++,qt,qpainter,qheaderview

It is obvious why the first fillRect doesn't work. Everything that you paint before paintSection is overridden by base painting. The second call is more interesting. Usually all paint methods preserves painter state. It means that when you call paint it looks like the painter state hasn't been changed. Nevertheless..

Java how to limit number of threads acting on method

java,multithreading,memory-management

You can use the Executor.newFixedThreadPool idiom, internally to your execution logic. Full example below: public class Main { public static void main(String[] args) throws Exception { Main m = new Main(); // simulating a window of time where your method is invoked continuously for (int i = 0; i <..

Updating ac value for Qtimer

qt,user-interface,adc

Hopefully this will get you started - it creates a timer which times out every 1000 milli seconds. The timer's timeout signal is connected to the same slot that your PushButton1 is connected to - starti2c. QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(starti2c())); timer->start(1000); That code should be..

Unable to connect to mariadb database server with qt 4.8.5 and Ubuntu 12.04

mysql,qt,ubuntu,mariadb

It was a problem with the database and not the Qt application, the connection refused if a password was used.

Must compile Opencv with Mingw in order to use in QT under Winodws?

qt,opencv,mingw

You can compile it with Visual Studio as well. The opencv includepaths already have the opencv2 part of it. So the correct includepath would only be: C:opencv2.4.11opencvbuildinclude ..

Change attribute value of an XML tag in Qt

c++,xml,qt

I guess, but I think your XML is only present in your memory. You have to trigger somethink like tsFileXml.WriteToFile(filename) to store your changes to a file on your filesystem.

Pro file directive: copy target to folder at build step

qt,qt5

Create DestDir.pri in folder, where all of your projects located. Insert next code: isEmpty(DESTDIR) { CONFIG(debug, debug|release) { DESTDIR=$$PWD/Build/Debug } CONFIG(release, debug|release) { DESTDIR=$$PWD/Build/Release } } Include DestDir.pri to each pro file: include(./DestDir.pri) You can change DESTDIR variable to your path or set this variable via qmake command line utils..

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for..

Crystal convert the idea behind Thread pool to Fibers/spawn

multithreading,coroutine,crystal-lang

Something like this: require 'socket' ch = Channel(TCPSocket).new 10.times do spawn do loop do socket = ch.receive socket.puts 'Hi!' socket.close end end end server = TCPServer.new(1234) loop do socket = server.accept ch.send socket end This code will pre-spawn 10 fibers to attend the requests. The channel is unbuffered so the..

Images not appearing on WPF form when loading asynchronously

c#,wpf,multithreading,listbox,backgroundworker

@Clemens answer from his comment on the original question provided the solution. Ensuring that the file stream was being closed responsibly and changing the BitmapCacheOption to OnLoad now shows each image in the asynchronous load. The final code for the asynchronous load looks like: private void LoadAsync(object sender, DoWorkEventArgs e)..

java multithreading start() and run() [duplicate]

java,multithreading

We cannot predicate output order in case of Threads. Multithreading t1 = new Multithreading(); Multithreading t2 = new Multithreading(); t1.start(); // Thread is executing your run() method t2.run(); // It is a normal execution of run() method. No Thread is here ..

How does the kernel separate threads from processes

linux,multithreading,linux-kernel

Unlike Windows, Linux does not have an implementation of 'threads' in the kernel. The kernel gives us what are sometimes called 'lightweight processes', which are a generalization of the concepts of 'processes' and 'threads', and can be used to implement either. It may be confusing when you read kernel code..

Qstring error. Saving from Textpool to string

c++,qt,qstring

http://doc.qt.io/qt-4.8/qlineedit.html#text-prop textChanged is a signal that you can send when the text changes Use QString text() const instead Another useful method: modified : bool to check if the text was modified by the user Update to answer additional comment questions: It is best to declare all variables as private. Add..

Node.js and C/C++ integration: how to properly implement callbacks?

c++,node.js,multithreading

Calling callback from a different thread is not an options, v8 doesn't allow that. So you have to go with b. It's not so hard to implement actually. I recommend to use nan for this task. Here is an example from docs: class PiWorker : public NanAsyncWorker { public: PiWorker(NanCallback..

Id in database using qt

database,qt,sqlite

The method you're looking for is QSqlQuery::lastInsertId(). To quote the documentation: Returns the object ID of the most recent inserted row if the database supports it. An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back..

Multi-Threading error when binding a StringProperty

java,multithreading,javafx,javafx-8

It is wrong to call code that results in changes to the UI from a thread other than the FX Application Thread, regardless of whether or not it throws an exception. The FX toolkit makes a best effort to throw an exception if you violate this rule, but in some..

Return const reference to local variable correctly

c++,qt

Best starting hands in hold'em poker. It doesn't work. That way you simply suppress the warning by making the situation harder to analyze. The behavior is still undefined.

How to avoid user to click outside popup Dialog window using Qt and Python?

qt,user-interface,python-3.x,dialog,qt-creator

use setModal() like so; dialog.setModal(1); Or; dialog.setModal(true); ..

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue queue = new ConcurrentQueue(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //..

What happens if all node.js's worker threads are busy

javascript,node.js,multithreading

I/O in general does not block the event loop (there are some exceptions like the crypto module currently and things like fs.*Sync() methods) and especially in the case of network I/O, the libuv thread pool is not used at all (only for things like dns (currently) and fs operations). If..

How can I know the lock information in java?

java,multithreading,locking

You can use ThreadInfo#getLockedSynchronizers() (JavaDoc) via ThreadMXBean to get array of LockInfo on currently owned locks on threads. LockInfo will tell you just class name & identity hashcode of a lock, but that's sufficient in tracing lock objects.

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api

For context related problems, you can use CallContext.LogicalSetData and CallContext.LogicalGetData, which is merely an IDictionary which flows between contexts, and has a copy-on-write (shallow copy) semantics. Since your data is immutable (according to the docs), you can map your correlation id to your threads managed thread id: protected async..

How to add a gif image in the statusbar Qt [closed]

c++,qt

You can add a QLabel, with a QMovie in it. QLabel label; QMovie *movie = new QMovie('animations/fire.gif'); label.setMovie(movie); movie->start(); You can then add the label to the using QStatusBar::addWidget() like so: statusBar()->addWidget(&label); ..

Why does this code catch block not execute?

c++,multithreading,error-handling,try-catch

You forgot to join the thread : try { thread t(do_work); t.join(); // <<< add this std::cerr << 'THROWING' << std::endl; throw logic_error('something went wrong'); } catch (logic_error e) { std::cerr << 'GOTCHA' << std::endl; } A joinable thread that goes out of scope, causes terminate to be called. So,..

Using QSimpleXmlNodeModel and QTreeView

c++,qt

There is an example delivered with Qt. Take a look at xmlpatterns/filetree example. It is not that easy as with some other models. You have to implement these abstract methods: QUrl QAbstractXmlNodeModel::documentUri(const QXmlNodeModelIndex &) const QXmlNodeModelIndex::NodeKind QAbstractXmlNodeModel::kind(const QXmlNodeModelIndex &) const QXmlNodeModelIndex::DocumentOrder QAbstractXmlNodeModel::compareOrder(const QXmlNodeModelIndex &,const QXmlNodeModelIndex &) const QXmlNodeModelIndex QAbstractXmlNodeModel::root(const..

wait for an event regulary

multithreading,events

I solve it I use threading and producer/consumer problem. after an event it will wait until event method run.

Invoke form showdialog is not modal

vb.net,multithreading,invoke

in the showDialog, you can set the parent form which causes the child to become modal: Public Class MainForm Dim frm2 As Form2 Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load frm2 = New Form2() Dim frmHandle As IntPtr = frm2.Handle frm2.Button1.Text = 'test' System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)..

How can we make a thread to sleep for a infinite time in java?

java,multithreading,thread-sleep

Probably Thread.sleep(Long.MAX_VALUE) is enough, but if you want to make sure: while (true) { Thread.sleep(Long.MAX_VALUE); } ..

connecting signals and slots with different relations

c++,qt,connect,signals-slots

You need to create new slot for that purpose. But in C++ 11 and Qt 5 style you can use labmdas! It is very comfortable for such short functions. In your case: connect(ui->horizontalSlider, &QSlider::sliderMoved, this, [this](int x) { this->ui->progressBar->setValue(x / 2); }); ..

Rotating a Label In Qt with Python

python,qt

Not 100% sure what you're trying to achieve, but rotating the image / pixmap and leaving the label's paintEvent unchanged seems easier: # load your image image = QtGui.QPixmap(_fromUtf8(':/icons/BOOM_OUT.png')) # prepare transform t = QtGui.QTransform() t.rotate(45) # rotate the pixmap rotated_pixmap = pixmap.transformed(t) # and let the label show the..

QT Combo Box of Line Pattern

c++,qt,qcombobox

Easy way: comboBox->setIconSize(QSize(100, 24)); comboBox->addItem(lineIcon, '); comboBox->addItem(dotLineIcon, '); comboBox->addItem(dashLineIcon, '); .. Correct way: comboBox->setItemDelegate(..); ..

Repeat state on mouse click QML

qt,qml,qtquick2

States are a way to represent different property configurations for a given Item. Each State has its unique set of values for the properties defined inside the specific Item. Transitions are a way to add animations to an Item when the current State changes to another State. They can be..

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

ios,objective-c,multithreading,swift,grand-central-dispatch

This will not deadlock since the dispatched block can start running immediately - it's not a serial queue so it doesn't have to wait for the current block to finish. But it's still not a good idea. This will block one thread causing the OS to spin up a new..

std::condition_variable – notify once but wait thread wakened twice

c++,multithreading

Converting comments into answer: condition_variable::wait(lock, pred) is equivalent to while(!pred()) wait(lock);. If pred() returns true then no wait actually takes place and the call returns immediately. Your first wake is from the notify_one() call; the second 'wake' is because the second wait() call happens to execute after the Stop() call,..

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic

As long as your used memory order is at least acquire/release (which is the default), you are guaranteed to see all updates (not just the ones to atomic variables) the writing thread did before setting the flag to true as soon as you can read the write. So yes, this..

How can I override the member of (->) operator of a base class

c++,qt,inheritance,overloading,operator-keyword

As I eventually realised above, this isn't possible. The operator ->() has to return the type upon which it is acting, and for that reason it can't be used as a virtual function.

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch

dispatch_sync will block the caller thread until execution completes, a concurrent queue has multiple threads so it will only block one of those on that queue, the other threads will still execute. Here is what Apple says about this: Submits a block to a dispatch queue for synchronous execution. Unlike..

Remarks

A few notes that are already mentioned in the official docs here and here:

  • If an object has a parent, it has to be in the same thread as the parent, i.e. it cannot be moved to a new thread, nor can you set a parent to an object if the parent and the object live in different threads
  • When an object is moved to a new thread, all of its children are also moved to the new thread
  • You can only push objects to a new thread. You cannot pull them to a new thread, i.e. you can only call moveToThread from the thread where the object is currently living in

Basic usage of QThread

QThread is a handle to a platform thread. It lets you manage the thread by monitoring its lifetime, and requesting that it finishes its work.

In most cases inhering from the class is not recommended. The default run method starts an event loop that can dispatch events to objects living in the class. Cross-thread signal-slot connections are implemented by dispatching a QMetaCallEvent to the target object.

A QObject instance can be moved to a thread, where it will process its events, such as timer events or slot/method calls.

To do work on a thread, first create your own worker class that derives from QObject. Then move it to the thread. The object can run its own code automatically e.g. by using QMetaObject::invokeMethod().

If your worker should be ephemeral and only exist while its work is being done, it's best to submit a functor or a thread-safe method for execution in the thread pool via QtConcurrent::run.

Irs gambling tax form
  • The Qt signals/slots and property system are based on the ability to introspect the objects at runtime. Introspection means being able to list the methods and properties of an object and have all kinds of information about them such as the type of their arguments. QtScript and QML would have hardly been possible without that ability.
  • As QAbstractItemView uses AutoConnections, the signals will be queued if they are in another thread. So, AFAIU, the model and view must be in the same thread if things are not to break. It's not impossible that a model would try to insert and remove rows in quick succession.
  • 8BiTs 매일 코딩 홈페이지. (Qt) Cross Thread Signal and Slots - 2 Get Code.
  • Qt documentation states that signals and slots can be direct, queued and auto. It also stated that if object that owns slot ‘lives' in a thread different from object that owns signal, emitting such signal will be like posting message – signal emit will return instantly and slot method will be called in target thread's event loop.

I am implementing a small project where I am extensively using QThreads and signals/slots (and basically Qt 5). I can say I have a fair idea about how signals/slots work along with QThreads. (I have gone through all important material on StackExchange as well as these links 'You are doing it wrong' and its update You were not doing so wrong. I have also gone through Most correct way to use QThread) I am convinced about my design that I will have to subclass QThread but also add slots to the subclass (which I know will run in separate threads.)

My calling thread (object on the thread) hosts such slots of at least three different classes along with its own utility functions. My question is: How the context switches between different slots and functions affined to a thread are handled? Will there be a context switch if one of the function has sleep or wait called (should be right?)? Secondly is there anything specific behaviour for QThreads?

If there is nothing specific to Qt or QThreads, still I would like to know about this behaviour in general. Thanks in advance.

I think that you're confused by the cooperative multitasking exhibited by typical event driven applications, with their run-to-completion event handlers. This is how WIN16, GEM and other such platforms appeared to multitask with no context switches at all.

I'll attempt to clear this confusion after exposing the necessary background to this story.

A context switch is a way to reuse an available core to run another thread when the current one has used up its timeslice or is sleeping. It is an optimization of sort, when you're short on cores. Yes, it is an implementation detail of the platform that your code runs on. It is not even a necessary one: you cannot tell if your platform context-switches or not just by looking at it (really, other then side channel attacks).

QThread is just a thin thread controller object. The controlled thread is a platform object and Qt does nothing to alter its behavior. The QThread::run behaves just like it would on a native platform thread, because that's where it runs.

The QThread::run method only spins (exec() in Qt parlance) an event loop (of course it won't do it anymore if your reimplementation doesn't).

An event loop waits for events to arrive in the queue, and then notifies the target QObjects of their reception.

The cross-thread (queued) signal-slot connections are implemented by leveraging events. Upon emission, the signal copies its arguments and posts them in a QMetaCallEvent to each queued-connected receiver object. Since these objects live in another thread, the event loop running in their thread will get woken up. It will then pick up the event and have it handled by the target object's event method. Specifically, QObject::event implementation knows how to deal with the QMetaCallEvent: it will execute the slot call.

Thus, queued slot calls are acting as event handlers, since they are invoked as an effect of QObject::event() being invoked by the event loop. Whenever a queued slot executes, the call stack looks as follows:

  • your slot method,
  • QObject::event()
  • ..
  • QEventLoop::exec()
  • QThread::run
  • platform-specific thread function.

So, how can events and event handlers give an impression of multiprocessing? That's because all event handlers are running to completion. They never sleep nor block, they simply execute the short actions they need to, and immediately return to the event loop.

This behavior will be broken as soon as your event handlers become blocking. Since slots called via queued connections (cross-thread) are effectively QMetaCallEvent handlers, if you block/sleep/wait in them, you're sleeping the entire thread. Suppose you call QThread::sleep in your slot. The call stack then is:

  • platform-specific implementation of sleep,
  • QThread::sleep(),
  • your slot,
  • ..
  • QThread::run().

At this point, the thread simply isn't runnable. If the platform so chooses, another thread might run on the same core, to make use of it, but that is the platform's optional optimization that you have little control over.

  1. How the context switches between different slots and functions affined to a thread are handled?

    There are none. Or, more specifically, as long as there are QMetaCallEvent events stored in the event queue for a given thread, and as long as that thread is runnable, it will simply keep executing the queued slot calls. On an otherwise idle multicore machine, you can keep a thead executing queued slot calls with no additional context switches.

    If your slot sleeps or waits, the entire thread sleeps or waits.

  2. Will there be a context switch if one of the function has sleep or wait called?

    Not necessarily so. You're presuming that the operating system's implementation of interruptible wait will preempt your thread. This might be the case, or it might not be the case. Whatever happens, of course, your thread is sleeping at that point and obviously nothing else happens within it while it is sleeping.

Copy text and placeholders, variables to the clipboard

c++,qt,clipboard

You're not using the function setText correctly. The canonical prototype is text(QString & subtype, Mode mode = Clipboard) const from the documentation. What you want to do is assemble your QString ahead of time and then use that to populate the clipboard. QString message = QString('Just a test text. And..

Any way to catch an exception occurring on a thread I don't own?

c#,multithreading,exception

The thing worrying me most in the described case is abnormal thread termination inside that 3rd-party lib. Once a thread is throwing, you can't catch the exception via correct way because you're not the owner of that thread invocation (and it has no idea it should propagate the exception to..

How to pass QString variable to QFile?

qt,qstring,qfile

QString selected = model2->filePath(index); does not set the variable in the (maybe same named) member OptionsDialog::selected. This creates a new local variable. If you have a member variable called selected then you should use it like this: void OptionsDialog::getData(const QModelIndex &index) { selected = model2->filePath(index); .. } ..

Does wait() need synchronization on local variable

java,multithreading,synchronization

I don't know Android development tools, but the warning sounds over-zealous. The compiler is trying to help you to avoid synchronizing on an instance that is only visible to a single thread. It's smart enough to know that the local variable, r, can only be seen by one thread, but..

Set Label From Thread

vb.net,multithreading,winforms

The reason is that you are referring to the default instance in your second code snippet. Default instances are thread-specific so that second code snippet will create a new instance of the Form1 type rather then use the existing instance. Your Class1 needs a reference to the original instance of..

How can I have an animated system tray icon in PyQt4?

python,qt,pyqt,pyqt4,system-tray Ok google give me free slot machines without.

Maybe something like this. Create QMovie instance to be used by AnimatedSystemTrayIcon. Connect to the frameChanged signal of the movie and call setIcon on the QSystemTrayIcon. You need to convert the pixmap returned by QMovie.currentPixmap to a QIcon to pass to setIcon. Disclaimer, only tested on Linux. import sys from..

Looking to pause a thread using thread.sleep

java,multithreading

You're probably running into a race condition between the two threads, the fact that i isn't volatile also suggests that the threads may not be working with the same actual value as each other. Threads are also non-reentrant, meaning that once the run method exists, they can not be restarted..

Java 5 Multi threading, catch thread exceptions

java,multithreading,exception,concurrency,java-5

The most common approach is to submit a Callable to an Executor, and receive a Future. You can then call Future.get to find out if any exceptions were thrown. As for UncaughtExceptionHandler, you can only really use it with raw threads because Executors handle uncaught exceptions internally (thus you don't..

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread

c++,multithreading,sorting,recursion

You problem originates in this line: int newArray[maxCount + 1]; You are trying to allocate ~250000 ints on the stack (on most 32 bit platforms it will take ~1MB of memory). Your thread's stack may not be able to do this. By the way, you should not do this -..

change QDir::rootPath() to program running path?

c++,qt

QCoreApplication::applicationDirPath() returns the exact directory path of your app, for example H:/programs if your app path is H:/programs/ftpserver.exe so if you modify that QString you can get the root dir. For example: QString rootPath = QCoreApplication::applicationDirPath(); rootPath.chop(rootPath.length() - 3); //we leave the 3 first characters of the path, the root..

How to differentiate a QNetworkReply is aborted or not?

c++,qt,networking

If aborted, QNetworkReply::error() should return QNetworkReply::OperationCanceledError, which means: the operation was canceled via calls to abort() or close() before it was finished. ..

Is there standard implementation for thread block/resume in java SE?

java,multithreading,wait

have a a look at the classes in java.util.conucurrent .. CountDownLatch might be a solution for your problem if i understand your problem correctly.

Multiple Threads searching on same folder at same time

c#,multithreading,file-search

Instead of using ordinary foreach statement in doing your search, you should use parallel linq. Parallel linq combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library. This will shield you from low level thread manipulation and..

What does QHeaderView::paintSection do such that all I do to the painter before or after is ignored

c++,qt,qpainter,qheaderview

It is obvious why the first fillRect doesn't work. Everything that you paint before paintSection is overridden by base painting. The second call is more interesting. Usually all paint methods preserves painter state. It means that when you call paint it looks like the painter state hasn't been changed. Nevertheless..

Java how to limit number of threads acting on method

java,multithreading,memory-management

You can use the Executor.newFixedThreadPool idiom, internally to your execution logic. Full example below: public class Main { public static void main(String[] args) throws Exception { Main m = new Main(); // simulating a window of time where your method is invoked continuously for (int i = 0; i <..

Updating ac value for Qtimer

qt,user-interface,adc

Hopefully this will get you started - it creates a timer which times out every 1000 milli seconds. The timer's timeout signal is connected to the same slot that your PushButton1 is connected to - starti2c. QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(starti2c())); timer->start(1000); That code should be..

Unable to connect to mariadb database server with qt 4.8.5 and Ubuntu 12.04

mysql,qt,ubuntu,mariadb

It was a problem with the database and not the Qt application, the connection refused if a password was used.

Must compile Opencv with Mingw in order to use in QT under Winodws?

qt,opencv,mingw

You can compile it with Visual Studio as well. The opencv includepaths already have the opencv2 part of it. So the correct includepath would only be: C:opencv2.4.11opencvbuildinclude ..

Change attribute value of an XML tag in Qt

c++,xml,qt

I guess, but I think your XML is only present in your memory. You have to trigger somethink like tsFileXml.WriteToFile(filename) to store your changes to a file on your filesystem.

Pro file directive: copy target to folder at build step

qt,qt5

Create DestDir.pri in folder, where all of your projects located. Insert next code: isEmpty(DESTDIR) { CONFIG(debug, debug|release) { DESTDIR=$$PWD/Build/Debug } CONFIG(release, debug|release) { DESTDIR=$$PWD/Build/Release } } Include DestDir.pri to each pro file: include(./DestDir.pri) You can change DESTDIR variable to your path or set this variable via qmake command line utils..

C++ & Qt: Random string from an array area

c++,arrays,string,qt,random

You should use the random header. #include std::default_random_engine generator; std::uniform_int_distribution dist(0, 5); int StringIndex = dist(generator); std::string ChosenString = characters[StringIndex]; The above will generate a random index into your array. If you want to limit the range, change the constructor of dist, for example (dist(0,2) would only allow for..

Crystal convert the idea behind Thread pool to Fibers/spawn

multithreading,coroutine,crystal-lang

Something like this: require 'socket' ch = Channel(TCPSocket).new 10.times do spawn do loop do socket = ch.receive socket.puts 'Hi!' socket.close end end end server = TCPServer.new(1234) loop do socket = server.accept ch.send socket end This code will pre-spawn 10 fibers to attend the requests. The channel is unbuffered so the..

Images not appearing on WPF form when loading asynchronously

c#,wpf,multithreading,listbox,backgroundworker

@Clemens answer from his comment on the original question provided the solution. Ensuring that the file stream was being closed responsibly and changing the BitmapCacheOption to OnLoad now shows each image in the asynchronous load. The final code for the asynchronous load looks like: private void LoadAsync(object sender, DoWorkEventArgs e)..

java multithreading start() and run() [duplicate]

java,multithreading

We cannot predicate output order in case of Threads. Multithreading t1 = new Multithreading(); Multithreading t2 = new Multithreading(); t1.start(); // Thread is executing your run() method t2.run(); // It is a normal execution of run() method. No Thread is here ..

How does the kernel separate threads from processes

linux,multithreading,linux-kernel

Unlike Windows, Linux does not have an implementation of 'threads' in the kernel. The kernel gives us what are sometimes called 'lightweight processes', which are a generalization of the concepts of 'processes' and 'threads', and can be used to implement either. It may be confusing when you read kernel code..

Qstring error. Saving from Textpool to string

c++,qt,qstring

http://doc.qt.io/qt-4.8/qlineedit.html#text-prop textChanged is a signal that you can send when the text changes Use QString text() const instead Another useful method: modified : bool to check if the text was modified by the user Update to answer additional comment questions: It is best to declare all variables as private. Add..

Node.js and C/C++ integration: how to properly implement callbacks?

c++,node.js,multithreading

Calling callback from a different thread is not an options, v8 doesn't allow that. So you have to go with b. It's not so hard to implement actually. I recommend to use nan for this task. Here is an example from docs: class PiWorker : public NanAsyncWorker { public: PiWorker(NanCallback..

Id in database using qt

database,qt,sqlite

The method you're looking for is QSqlQuery::lastInsertId(). To quote the documentation: Returns the object ID of the most recent inserted row if the database supports it. An invalid QVariant will be returned if the query did not insert any value or if the database does not report the id back..

Multi-Threading error when binding a StringProperty

java,multithreading,javafx,javafx-8

It is wrong to call code that results in changes to the UI from a thread other than the FX Application Thread, regardless of whether or not it throws an exception. The FX toolkit makes a best effort to throw an exception if you violate this rule, but in some..

Return const reference to local variable correctly

c++,qt

Best starting hands in hold'em poker. It doesn't work. That way you simply suppress the warning by making the situation harder to analyze. The behavior is still undefined.

How to avoid user to click outside popup Dialog window using Qt and Python?

qt,user-interface,python-3.x,dialog,qt-creator

use setModal() like so; dialog.setModal(1); Or; dialog.setModal(true); ..

performance issues executing list of stored procedures

c#,multithreading,performance,loops

What I would do is something like this: int openThread = 0; ConcurrentQueue queue = new ConcurrentQueue(); foreach (var sp in lstSps) { Thread worker = new Thread(() => { Interlocked.Increment(ref openThread); if(sp.TimeToRun() && sp.HasResult) { queue.add(sp); } Interlocked.Decrement(ref openThread); }) {Priority = ThreadPriority.AboveNormal, IsBackground = false}; worker.Start(); } //..

What happens if all node.js's worker threads are busy

javascript,node.js,multithreading

I/O in general does not block the event loop (there are some exceptions like the crypto module currently and things like fs.*Sync() methods) and especially in the case of network I/O, the libuv thread pool is not used at all (only for things like dns (currently) and fs operations). If..

How can I know the lock information in java?

java,multithreading,locking

You can use ThreadInfo#getLockedSynchronizers() (JavaDoc) via ThreadMXBean to get array of LockInfo on currently owned locks on threads. LockInfo will tell you just class name & identity hashcode of a lock, but that's sufficient in tracing lock objects.

Web API - Set each thread with the HttpRequestMessage id?

c#,.net,multithreading,task-parallel-library,web-api

For context related problems, you can use CallContext.LogicalSetData and CallContext.LogicalGetData, which is merely an IDictionary which flows between contexts, and has a copy-on-write (shallow copy) semantics. Since your data is immutable (according to the docs), you can map your correlation id to your threads managed thread id: protected async..

How to add a gif image in the statusbar Qt [closed]

c++,qt

You can add a QLabel, with a QMovie in it. QLabel label; QMovie *movie = new QMovie('animations/fire.gif'); label.setMovie(movie); movie->start(); You can then add the label to the using QStatusBar::addWidget() like so: statusBar()->addWidget(&label); ..

Why does this code catch block not execute?

c++,multithreading,error-handling,try-catch

You forgot to join the thread : try { thread t(do_work); t.join(); // <<< add this std::cerr << 'THROWING' << std::endl; throw logic_error('something went wrong'); } catch (logic_error e) { std::cerr << 'GOTCHA' << std::endl; } A joinable thread that goes out of scope, causes terminate to be called. So,..

Using QSimpleXmlNodeModel and QTreeView

c++,qt

There is an example delivered with Qt. Take a look at xmlpatterns/filetree example. It is not that easy as with some other models. You have to implement these abstract methods: QUrl QAbstractXmlNodeModel::documentUri(const QXmlNodeModelIndex &) const QXmlNodeModelIndex::NodeKind QAbstractXmlNodeModel::kind(const QXmlNodeModelIndex &) const QXmlNodeModelIndex::DocumentOrder QAbstractXmlNodeModel::compareOrder(const QXmlNodeModelIndex &,const QXmlNodeModelIndex &) const QXmlNodeModelIndex QAbstractXmlNodeModel::root(const..

wait for an event regulary

multithreading,events

I solve it I use threading and producer/consumer problem. after an event it will wait until event method run.

Invoke form showdialog is not modal

vb.net,multithreading,invoke

in the showDialog, you can set the parent form which causes the child to become modal: Public Class MainForm Dim frm2 As Form2 Private Sub MainForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load frm2 = New Form2() Dim frmHandle As IntPtr = frm2.Handle frm2.Button1.Text = 'test' System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf DoSomething), 0)..

How can we make a thread to sleep for a infinite time in java?

java,multithreading,thread-sleep

Probably Thread.sleep(Long.MAX_VALUE) is enough, but if you want to make sure: while (true) { Thread.sleep(Long.MAX_VALUE); } ..

connecting signals and slots with different relations

c++,qt,connect,signals-slots

You need to create new slot for that purpose. But in C++ 11 and Qt 5 style you can use labmdas! It is very comfortable for such short functions. In your case: connect(ui->horizontalSlider, &QSlider::sliderMoved, this, [this](int x) { this->ui->progressBar->setValue(x / 2); }); ..

Rotating a Label In Qt with Python

python,qt

Not 100% sure what you're trying to achieve, but rotating the image / pixmap and leaving the label's paintEvent unchanged seems easier: # load your image image = QtGui.QPixmap(_fromUtf8(':/icons/BOOM_OUT.png')) # prepare transform t = QtGui.QTransform() t.rotate(45) # rotate the pixmap rotated_pixmap = pixmap.transformed(t) # and let the label show the..

QT Combo Box of Line Pattern

c++,qt,qcombobox

Easy way: comboBox->setIconSize(QSize(100, 24)); comboBox->addItem(lineIcon, '); comboBox->addItem(dotLineIcon, '); comboBox->addItem(dashLineIcon, '); .. Correct way: comboBox->setItemDelegate(..); ..

Repeat state on mouse click QML

qt,qml,qtquick2

States are a way to represent different property configurations for a given Item. Each State has its unique set of values for the properties defined inside the specific Item. Transitions are a way to add animations to an Item when the current State changes to another State. They can be..

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?

ios,objective-c,multithreading,swift,grand-central-dispatch

This will not deadlock since the dispatched block can start running immediately - it's not a serial queue so it doesn't have to wait for the current block to finish. But it's still not a good idea. This will block one thread causing the OS to spin up a new..

std::condition_variable – notify once but wait thread wakened twice

c++,multithreading

Converting comments into answer: condition_variable::wait(lock, pred) is equivalent to while(!pred()) wait(lock);. If pred() returns true then no wait actually takes place and the call returns immediately. Your first wake is from the notify_one() call; the second 'wake' is because the second wait() call happens to execute after the Stop() call,..

Atomic/not-atomic mix, any guarantees?

c++,multithreading,c++11,atomic

As long as your used memory order is at least acquire/release (which is the default), you are guaranteed to see all updates (not just the ones to atomic variables) the writing thread did before setting the flag to true as soon as you can read the write. So yes, this..

How can I override the member of (->) operator of a base class

c++,qt,inheritance,overloading,operator-keyword

As I eventually realised above, this isn't possible. The operator ->() has to return the type upon which it is acting, and for that reason it can't be used as a virtual function.

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch

dispatch_sync will block the caller thread until execution completes, a concurrent queue has multiple threads so it will only block one of those on that queue, the other threads will still execute. Here is what Apple says about this: Submits a block to a dispatch queue for synchronous execution. Unlike..

Remarks

A few notes that are already mentioned in the official docs here and here:

  • If an object has a parent, it has to be in the same thread as the parent, i.e. it cannot be moved to a new thread, nor can you set a parent to an object if the parent and the object live in different threads
  • When an object is moved to a new thread, all of its children are also moved to the new thread
  • You can only push objects to a new thread. You cannot pull them to a new thread, i.e. you can only call moveToThread from the thread where the object is currently living in

Basic usage of QThread

QThread is a handle to a platform thread. It lets you manage the thread by monitoring its lifetime, and requesting that it finishes its work.

In most cases inhering from the class is not recommended. The default run method starts an event loop that can dispatch events to objects living in the class. Cross-thread signal-slot connections are implemented by dispatching a QMetaCallEvent to the target object.

A QObject instance can be moved to a thread, where it will process its events, such as timer events or slot/method calls.

To do work on a thread, first create your own worker class that derives from QObject. Then move it to the thread. The object can run its own code automatically e.g. by using QMetaObject::invokeMethod().

If your worker should be ephemeral and only exist while its work is being done, it's best to submit a functor or a thread-safe method for execution in the thread pool via QtConcurrent::run.

QtConcurrent Run

If you find managing QThreads and low-level primitives like mutexes or semaphores too complex, Qt Concurrent namespace is what you are looking for. It includes classes which allow more high-level thread management.

Let's look at Concurrent Run. QtConcurrent::run() allows to run function in a new thread. When would you like to use it? When you have some long operation and you don't want to create thread manually.

Qt Connect Signal Slot

Now the code:

So things are simple: when we need to run another function in another thread, just call QtConcurrent::run, pass function and its parameters and that's it!

Qt Signal Slot Cross Threaded

QFuture presents the result of our asynchronous computation. In case of QtConcurrent::run we can't cancel the function execution.

Invoking slots from other threads

When a Qt event loop is used to perform operations and a non-Qt-saavy user needs to interact with that event loop, writing the slot to handle regular invocations from another thread can simplify things for other users.

main.cpp:

OperationExecutioner.h:

OperationExecutioner.cpp:

OperationExecutioner.pro:

Qt Signal Slot Example






broken image