Qt Run Slot In Another Thread
- Qt Run Slot In Another Threaded
- Qt Run Slot In Another Thread Size
- Qt Run Slot In Another Thread Set
- Qt Run Slot In Another Thread Pattern
- Creating a class and moving it to a thread in a different QThread prevents QWebChannel's queued interaction. To Reproduce: Implement a new class which contains at least 1 public slot (void return) Create an instance of custom class derived from QObject myClass; Create an instance of QThread myClassThread.
- A short history. Long long ago, subclass QThread and reimplement its run function is the only recommended way of using QThread. This is rather intuitive and easy to used. But when SLOTS and Qt event loop are used in the worker thread, some users do it wro.
Just inherit QThread class and override run method. Now while you call start slot through an instance of the inherited class, then while your overrided run get execution, another thread of control is begin with the starting point as run method. That is, run method execution life cycle (scope) run on another thread. Then this might be possible. However, the signal-slot mimic will more or less generate a direct function call which will be executed in the thread you are emitting the signal. I do not see a way to tell the thread that it has to execute the function in another thread. I guess you need to separate the different tasks in two objects.
how in BOOST send a signal in a thread and have the corresponding slot executed in another thread?
boost::signals2::signal
boost signal handler
boost signal multi-threaded
boost multithreading
In Qt for instance if you emit a signal in a thread other that the GUI thread, the signal is enqueued and executed later in the GUI thread, is there a way to do that with boost?
thanks
For an event loop use boost::asio::io_service. You can post tasks inside this object and have another thread execute them, in a thread safe way:
Messaging and Signaling in C++, But as this blog post is more on signaling then system events. Qt signal/slot implementation is thread safe, so that you can use it to send messages important, as anything UI related should run in the main thread of Qt, anything that I use this in a different program to have one widget for editing flag like Almost all classes provided by Boost.Signals2 are thread safe and can be used in multithreaded applications. For example, objects of type boost::signals2::signal and boost::signals2::connection can be accessed from different threads. On the other hand, boost::signals2::shared_connection_block is not thread safe.
Not directly, because boost does not provide an event loop.
To have a signal handled in another thread, that another thread needs to be checking the queue of handlers it should run and execute them (which usually means some kind of event-loop). Boost does not provide one, so you'll need to get it from elsewhere or write it.
If you have an event-loop, that does not provide signals, (or implement some simple solution with queues) you should be able to (ab)use boost.signals2 (not boost.signals, because that version is not thread-safe) by overriding the operator+=
to wrap each handler in something, that will queue it for execution in the other thread. You might even be able to implement it for signals with return values (which is not supported by Qt, but is supported by boost), but you'll have to be careful to avoid dead-lock.
[PDF] Boost.Signals2, Signals2 library is an implementation of a managed signals and slots system. This documentation describes a thread-safe variant of the original Boost. so we put 'Hello' into a group that must be executed before the group possible to set up tracking in a post-constructor which is called after the object has been created To have a signal handled in another thread, that another thread needs to be checking the queue of handlers it should run and execute them (which usually means some kind of event-loop). Boost does not provide one, so you'll need to get it from elsewhere or write it.
Signals & Slots, Signals and slots are made possible by Qt's meta-object system. to one signal, the slots will be executed one after the other, in the order they have valueChanged() , and it has a slot which other objects can send signals to. The context object provides information about in which thread the receiver should be executed. Special behavior for C++: If a thread is sent a signal using pthread_kill() and that thread does not handle the signal, then destructors for local objects may not be executed. Usage notes. The SIGTHSTOP and SIGTHCONT signals can be issued by this function. pthread_kill() is the only function that can issue SIGTHSTOP or SIGTHCONT. Returned value
Chila's answer is correct, but it's missing one important thing:A boost::thread
object will only call the function its passed once. Since the boost::io_service
has no work to do until the signal is emitted, the thread will finish immediately. To counter this there is a boost::asio::io_service::work
class.Before you call the run()
method of the io_service
you should create a work object and pass it the io_service
:
Note: At the time of writing (boost 1.67) this method is already deprecated and you are supposed to use io_context::executor_work_guard
(basically same functionality as io_service::work
). I was not able to compile when using the new method though, and the work solution is still working in boost 1.67.
Slots, It also implements a few conditional (event) related classes. Qt - SigSlot - Boost Libraries Qt was the original signal/slots implementation, but it Sigslot and Boost on the other hand are pure ISO C++, but both have some disadvantages. None of these are thread-safe and it can be somewhat inconvenient manually 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.
For some reason, the assignment operator of boost::asio::executor_work_guard<boost::asio::io_context::executor_type>
is deleted, but you still can construct it.
Here's my version of the code that posts some movable Event
object and processes it on the thread running io_context::run()
:
It requires C++14 and was tested with VS2017 and GCC 6.4 with thread & memory sanitizers.
Observer pattern with Stl, boost and qt, A comparison between the Qt signal and slot mechanism and some Each slot is a potential callback ○ Adds more run-time introspection, The Synapse library ○ Another signals/slot like library ○ Submitted to Very similar to boost::signals2 ○ Have the ability to transfer control between threads 29; 30. So, when the thread is created from the create_thread method it will call the io_service::run method and it passes the io_service object as an argument. Typically one io_service object can be used with multiple socket objects.
QThreads: Are You Using Them Wrong?, Show related SlideShares at end The Basics of QThread QThread manages one thread of execution ○ The Signal Slot Connections and Threads ○ Qt::DirectConnection have same thread affinity: Direct ○ If objects have different thread It implies you want to send cross-thread signals to yourself. Direct Connection The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread. Queued Connection The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
What do I do if a slot is not invoked?, A practical checklist to debug your signal/slot connections that an event loop is running in the thread the receiver has affinity with;; that all the arguments Using this signal is very easy – it just acts like a flag, but you can wait for it as well as read it. The following unit test (also in GitHub) shows how the signal makes it easy for threads to set gates on each other. Note that the final signal in this example could have been done with thread.join(), but wasn’t for the purposes of the test.
[Boost-users] Signals2 benchmark, I want to test it against boost::signals2 to get an idea of how well it performs. Suppose one thread disconnects a slot while another fires a signal Each Signal-type has its own corresponding vector of slots defined within the Emitter. the copy being made instead of every slot being called and executed. POSIX requires that signal is thread-safe, and specifies a list of async-signal-safe library functions that may be called from any signal handler. Signal handlers are expected to have C linkage and, in general, only use the features from the common subset of C and C++. It is implementation-defined if a function with C++ linkage can be used as a
Comments
- THX for this very helpfull sample ! Since boost::signal is deprecated I have to use boost::signals2::signal<>.
Hot Questions
The QThread class provides a platform-independent way to manage threads. More...
Header: | #include <QThread> |
qmake: | QT += core |
Inherits: | QObject |
Public Types
enum | Priority { IdlePriority, LowestPriority, LowPriority, NormalPriority, ..., InheritPriority } |
Public Functions
QThread(QObject *parent = nullptr) | |
virtual | ~QThread() |
QAbstractEventDispatcher * | eventDispatcher() const |
void | exit(int returnCode = 0) |
bool | isFinished() const |
bool | isInterruptionRequested() const |
bool | isRunning() const |
int | loopLevel() const |
QThread::Priority | priority() const |
void | requestInterruption() |
void | setEventDispatcher(QAbstractEventDispatcher *eventDispatcher) |
void | setPriority(QThread::Priority priority) |
void | setStackSize(uint stackSize) |
uint | stackSize() const |
bool | wait(unsigned long time = ULONG_MAX) |
Reimplemented Public Functions
- 32 public functions inherited from QObject
Public Slots
void | quit() |
void | start(QThread::Priority priority = InheritPriority) |
void | terminate() |
- 1 public slot inherited from QObject
Signals
- 2 signals inherited from QObject
Static Public Members
QThread * | create(Function &&f, Args &&... args) |
QThread * | create(Function &&f) |
QThread * | currentThread() |
Qt::HANDLE | currentThreadId() |
int | idealThreadCount() |
void | msleep(unsigned long msecs) |
void | sleep(unsigned long secs) |
const QMetaObject | staticMetaObject |
void | usleep(unsigned long usecs) |
void | yieldCurrentThread() |
- 10 static public members inherited from QObject
Protected Functions
- 9 protected functions inherited from QObject
Static Protected Members
void | setTerminationEnabled(bool enabled = true) |
Additional Inherited Members
- 1 property inherited from QObject
Detailed Description
The QThread class provides a platform-independent way to manage threads.
A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.
You can use worker objects by moving them to the thread using QObject::moveToThread().
The code inside the Worker's slot would then execute in a separate thread. However, you are free to connect the Worker's slots to any signal, from any object, in any thread. It is safe to connect signals and slots across different threads, thanks to a mechanism called queued connections.
Another way to make code run in a separate thread, is to subclass QThread and reimplement run(). For example:
In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().
It is important to remember that a QThread instance lives in the old thread that instantiated it, not in the new thread that calls run(). This means that all of QThread's queued slots and invoked methods will execute in the old thread. Thus, a developer who wishes to invoke slots in the new thread must use the worker-object approach; new slots should not be implemented directly into a subclassed QThread.
Unlike queued slots or invoked methods, methods called directly on the QThread object will execute in the thread that calls the method. When subclassing QThread, keep in mind that the constructor executes in the old thread while run() executes in the new thread. If a member variable is accessed from both functions, then the variable is accessed from two different threads. Check that it is safe to do so.
Note: Care must be taken when interacting with objects across different threads. See Synchronizing Threads for details.
Managing Threads
QThread will notifiy you via a signal when the thread is started() and finished(), or you can use isFinished() and isRunning() to query the state of the thread.
You can stop the thread by calling exit() or quit(). In extreme cases, you may want to forcibly terminate() an executing thread. However, doing so is dangerous and discouraged. Please read the documentation for terminate() and setTerminationEnabled() for detailed information.
From Qt 4.8 onwards, it is possible to deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater().
Use wait() to block the calling thread, until the other thread has finished execution (or until a specified time has passed).
QThread also provides static, platform independent sleep functions: sleep(), msleep(), and usleep() allow full second, millisecond, and microsecond resolution respectively. These functions were made public in Qt 5.0.
Note: 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.
The static functions currentThreadId() and currentThread() return identifiers for the currently executing thread. The former returns a platform specific ID for the thread; the latter returns a QThread pointer.
To choose the name that your thread will be given (as identified by the command ps -L
on Linux, for example), you can call setObjectName() before starting the thread. If you don't call setObjectName(), the name given to your thread will be the class name of the runtime type of your thread object (for example, 'RenderThread'
in the case of the Mandelbrot Example, as that is the name of the QThread subclass). Note that this is currently not available with release builds on Windows.
See also Thread Support in Qt, QThreadStorage, Synchronizing Threads, Mandelbrot Example, Semaphores Example, and Wait Conditions Example.
Member Type Documentation
enum QThread::Priority
This enum type indicates how the operating system should schedule newly created threads.
Constant | Value | Description |
---|---|---|
QThread::IdlePriority | 0 | scheduled only when no other threads are running. |
QThread::LowestPriority | 1 | scheduled less often than LowPriority. |
QThread::LowPriority | 2 | scheduled less often than NormalPriority. |
QThread::NormalPriority | 3 | the default priority of the operating system. |
QThread::HighPriority | 4 | scheduled more often than NormalPriority. |
QThread::HighestPriority | 5 | scheduled more often than HighPriority. |
QThread::TimeCriticalPriority | 6 | scheduled as often as possible. |
QThread::InheritPriority | 7 | use the same priority as the creating thread. This is the default. |
Member Function Documentation
QThread::QThread(QObject *parent = nullptr)
Constructs a new QThread to manage a new thread. The parent takes ownership of the QThread. The thread does not begin executing until start() is called.
See also start().
[virtual]
QThread::~QThread()
Destroys the QThread.
Note that deleting a QThread object will not stop the execution of the thread it manages. Deleting a running QThread (i.e. isFinished() returns false
) will result in a program crash. Wait for the finished() signal before deleting the QThread.
[static]
QThread *QThread::create(Function &&f, Args &&... args)
Creates a new QThread object that will execute the function f with the arguments args.
The new thread is not started -- it must be started by an explicit call to start(). This allows you to connect to its signals, move QObjects to the thread, choose the new thread's priority and so on. The function f will be called in the new thread.
Returns the newly created QThread instance.
Note: the caller acquires ownership of the returned QThread instance.
Note: this function is only available when using C++17.
Warning: do not call start() on the returned QThread instance more than once; doing so will result in undefined behavior.
This function was introduced in Qt 5.10.
See also start().
[static]
QThread *QThread::create(Function &&f)
Creates a new QThread object that will execute the function f.
The new thread is not started -- it must be started by an explicit call to start(). This allows you to connect to its signals, move QObjects to the thread, choose the new thread's priority and so on. The function f will be called in the new thread.
Returns the newly created QThread instance.
Note: the caller acquires ownership of the returned QThread instance.
Warning: do not call start() on the returned QThread instance more than once; doing so will result in undefined behavior.
This function was introduced in Qt 5.10.
See also start().
[static]
QThread *QThread::currentThread()
Returns a pointer to a QThread which manages the currently executing thread.
[static]
Qt::HANDLE QThread::currentThreadId()
Returns the thread handle of the currently executing thread.
Warning: The handle returned by this function is used for internal purposes and should not be used in any application code.
Note: On Windows, this function returns the DWORD (Windows-Thread ID) returned by the Win32 function GetCurrentThreadId(), not the pseudo-HANDLE (Windows-Thread HANDLE) returned by the Win32 function GetCurrentThread().
[override virtual]
bool QThread::event(QEvent *event)
Reimplemented from QObject::event().
QAbstractEventDispatcher *QThread::eventDispatcher() const
Returns a pointer to the event dispatcher object for the thread. If no event dispatcher exists for the thread, this function returns nullptr
.
This function was introduced in Qt 5.0.
See also setEventDispatcher().
[protected]
int QThread::exec()
Enters the event loop and waits until exit() is called, returning the value that was passed to exit(). The value returned is 0 if exit() is called via quit().
This function is meant to be called from within run(). It is necessary to call this function to start event handling.
See also quit() and exit().
void QThread::exit(intreturnCode = 0)
Tells the thread's event loop to exit with a return code.
After calling this function, the thread leaves the event loop and returns from the call to QEventLoop::exec(). The QEventLoop::exec() function returns returnCode.
By convention, a returnCode of 0 means success, any non-zero value indicates an error.
Note that unlike the C library function of the same name, this function does return to the caller -- it is event processing that stops.
No QEventLoops will be started anymore in this thread until QThread::exec() has been called again. If the eventloop in QThread::exec() is not running then the next call to QThread::exec() will also return immediately.
See also quit() and QEventLoop.
[signal]
void QThread::finished()
This signal is emitted from the associated thread right before it finishes executing.
When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater(), to free objects in that thread.
Note: If the associated thread was terminated using terminate(), it is undefined from which thread this signal is emitted.
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
See also started().
[static]
int QThread::idealThreadCount()
Returns the ideal number of threads that can be run on the system. This is done querying the number of processor cores, both real and logical, in the system. This function returns 1 if the number of processor cores could not be detected.
bool QThread::isFinished() const
Qt Run Slot In Another Threaded
Returns true
if the thread is finished; otherwise returns false
.
See also isRunning().
bool QThread::isInterruptionRequested() const
Return true if the task running on this thread should be stopped. An interruption can be requested by requestInterruption().
This function can be used to make long running tasks cleanly interruptible. Never checking or acting on the value returned by this function is safe, however it is advisable do so regularly in long running functions. Take care not to call it too often, to keep the overhead low.
This function was introduced in Qt 5.2.
See also currentThread() and requestInterruption().
bool QThread::isRunning() const
Returns true
if the thread is running; otherwise returns false
.
See also isFinished().
int QThread::loopLevel() const
Returns the current event loop level for the thread.
Note: This can only be called within the thread itself, i.e. when it is the current thread.
This function was introduced in Qt 5.5.
[static]
void QThread::msleep(unsignedlongmsecs)
Forces the current thread to sleep for msecs milliseconds.
Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).
Note: This function does not guarantee accuracy. The application may sleep longer than msecs under heavy load conditions. Some OSes might round msecs up to 10 ms or 15 ms.
See also sleep() and usleep().
QThread::Priority QThread::priority() const
Returns the priority for a running thread. If the thread is not running, this function returns InheritPriority
.
This function was introduced in Qt 4.1.
See also Priority, setPriority(), and start().
[slot]
void QThread::quit()
Tells the thread's event loop to exit with return code 0 (success). Equivalent to calling QThread::exit(0).
This function does nothing if the thread does not have an event loop.
See also exit() and QEventLoop.
void QThread::requestInterruption()
Request the interruption of the thread. That request is advisory and it is up to code running on the thread to decide if and how it should act upon such request. This function does not stop any event loop running on the thread and does not terminate it in any way.
This function was introduced in Qt 5.2.
See also isInterruptionRequested().
[virtual protected]
void QThread::run()
The starting point for the thread. After calling start(), the newly created thread calls this function. The default implementation simply calls exec().
You can reimplement this function to facilitate advanced thread management. Returning from this method will end the execution of the thread.
See also start() and wait().
void QThread::setEventDispatcher(QAbstractEventDispatcher *eventDispatcher)
Sets the event dispatcher for the thread to eventDispatcher. This is only possible as long as there is no event dispatcher installed for the thread yet. That is, before the thread has been started with start() or, in case of the main thread, before QCoreApplication has been instantiated. This method takes ownership of the object.
This function was introduced in Qt 5.0.
See also eventDispatcher().
void QThread::setPriority(QThread::Prioritypriority)
This function sets the priority for a running thread. If the thread is not running, this function does nothing and returns immediately. Use start() to start a thread with a specific priority.
The priority argument can be any value in the QThread::Priority
enum except for InheritPriorty
.
The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see http://linux.die.net/man/2/sched_setscheduler for more details).
This function was introduced in Qt 4.1.
See also Priority, priority(), and start().
void QThread::setStackSize(uintstackSize)
Sets the maximum stack size for the thread to stackSize. If stackSize is greater than zero, the maximum stack size is set to stackSize bytes, otherwise the maximum stack size is automatically determined by the operating system.
Warning: Most operating systems place minimum and maximum limits on thread stack sizes. The thread will fail to start if the stack size is outside these limits.
See also stackSize().
[static protected]
void QThread::setTerminationEnabled(boolenabled = true)
Enables or disables termination of the current thread based on the enabled parameter. The thread must have been started by QThread.
When enabled is false, termination is disabled. Future calls to QThread::terminate() will return immediately without effect. Instead, the termination is deferred until termination is enabled.
When enabled is true, termination is enabled. Future calls to QThread::terminate() will terminate the thread normally. If termination has been deferred (i.e. QThread::terminate() was called with termination disabled), this function will terminate the calling thread immediately. Note that this function will not return in this case.
See also terminate().
[static]
void QThread::sleep(unsignedlongsecs)
Forces the current thread to sleep for secs seconds.
Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).
Note: This function does not guarantee accuracy. The application may sleep longer than secs under heavy load conditions.
See also msleep() and usleep().
uint QThread::stackSize() const
Returns the maximum stack size for the thread (if set with setStackSize()); otherwise returns zero.
See also setStackSize().
[slot]
void QThread::start(QThread::Prioritypriority = InheritPriority)
Begins execution of the thread by calling run(). The operating system will schedule the thread according to the priority parameter. If the thread is already running, this function does nothing.
The effect of the priority parameter is dependent on the operating system's scheduling policy. In particular, the priority will be ignored on systems that do not support thread priorities (such as on Linux, see the sched_setscheduler documentation for more details).
See also run() and terminate().
[signal]
void QThread::started()
This signal is emitted from the associated thread when it starts executing, before the run() function is called.
Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.
See also finished().
[slot]
void QThread::terminate()
Terminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating system's scheduling policies. Use QThread::wait() after terminate(), to be sure.
When the thread is terminated, all threads waiting for the thread to finish will be woken up.
Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path. Threads can be terminated while modifying data. There is no chance for the thread to clean up after itself, unlock any held mutexes, etc. In short, use this function only if absolutely necessary.
Termination can be explicitly enabled or disabled by calling QThread::setTerminationEnabled(). Calling this function while termination is disabled results in the termination being deferred, until termination is re-enabled. See the documentation of QThread::setTerminationEnabled() for more information.
See also setTerminationEnabled().
[static]
void QThread::usleep(unsignedlongusecs)
Qt Run Slot In Another Thread Size
Forces the current thread to sleep for usecs microseconds.
Avoid using this function if you need to wait for a given condition to change. Instead, connect a slot to the signal that indicates the change or use an event handler (see QObject::event()).
Note: This function does not guarantee accuracy. The application may sleep longer than usecs under heavy load conditions. Some OSes might round usecs up to 10 ms or 15 ms; on Windows, it will be rounded up to a multiple of 1 ms.
Qt Run Slot In Another Thread Set
See also sleep() and msleep().
Qt Run Slot In Another Thread Pattern
bool QThread::wait(unsignedlongtime = ULONG_MAX)
Blocks the thread until either of these conditions is met:
- The thread associated with this QThread object has finished execution (i.e. when it returns from run()). This function will return true if the thread has finished. It also returns true if the thread has not been started yet.
- time milliseconds has elapsed. If time is ULONG_MAX (the default), then the wait will never timeout (the thread must return from run()). This function will return false if the wait timed out.
This provides similar functionality to the POSIX pthread_join()
function.
See also sleep() and terminate().
[static]
void QThread::yieldCurrentThread()
Yields execution of the current thread to another runnable thread, if any. Note that the operating system decides to which thread to switch.
© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.