简体   繁体   中英

How to emit signal from a thread and a seperate function can connect to the signal?

I want to create a thread and emit a signal from there after printing "Hello". Want to connect to the signal from a normal function or another thread that prints "World". How to do that in windows c++? Basically new to signal/slots communication.

There are two completely separate problems:

  1. Implementing signals in C++ and
  2. Calling function in another thread

Last time I mixed them I regretted it. Definitely recommended to solve separately; most signal handlers are likely to be synchronous anyway.

signals

  • C++11 introduced type-erased delegate, std::function , which can be used as delegate, creating collection of them for the signal isn't that much work. Handling connections/disconnections from separate thread is a bit more work though as is automatic disconnects on object destruction. Boost provides compatible implementation for C++03 environments.
  • Boost provides signals and signals2 library. The former does not handle disconnects from separate threads, so you probably want the later.
  • There is a small separate library, libsigc++ .
  • Qt contains elaborate signals and slots mechanism, that is unfortunately somewhat un-C++ (it comes from ancient times when C++ was not much more than C with classes).

calling function in separate thread

A thread is in sole control of what it executes. So if you want to execute something in another thread, you need to have an event loop running there. Since you can generally only run one event loop, you have to use the one that comes with your GUI library (there are not many reasons to want to run something in different thread except to get something done from the thread handling GUI as most GUI libraries are not thread-safe).

Qt allows you to specify a thread to run the handler in when connecting to a signal. In other frameworks you'll probably have to send some message into the event loop. You can use std::function to specify what to execute than.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM