C: How to make threads communicate with each other?

Interestingly, this seems to be the main question, and yet I couldn't find an example for it for the C language (in SO, I only found it for Python, C #, and C ++).

Point: as a Qt programmer, when I need to make some data to pass between different threads, I start a signal slot connection between them and use a mechanism emit signal

to get the job done.

But now I am working in a C application for Embedded Linux where I need to do a similar job, but I do not have a Qt engine. The question is, how can I make two or more threads interact with each other in C in a way similar to Qt with signals and slots?

I know that one way to exchange data is with globals with changes protected by mutexes. But even then, I probably won't be able to make the system asynchronous: I have to have a loop that will constantly check if a variable has changed or not. But what if I want to execute a specific method of a thread right after another, has completed some work (so, asynchronously)? Then it seems that this method fails.

Note. Although I am using Embedded Linux and therefore mention some options that will use POSIX features and other "Linux-related ways" it would be helpful, it would be better for the community if more time is devoted to solutions that are not strictly based on one specific platform (if possible).

+3


source to share


3 answers


Read a good tutorial on pthreads . You want to know more about condition variables that will be used with mutexes .

Condition variables and mutexes should probably be sufficient for your needs.



You can also use most of the traditional interprocess communication mechanisms between threads, for example. a pipe (7) (possibly polling (2) ...). So read Advanced Linux Programming and study syscalls (2) and pthreads (7)

Avoid using the (7) -s signal between threads.

+4


source


One way is to use message passing between threads via asynchronous queues. This way, you can avoid using shared data between threads, and only the queues need to be thread safe.

Asynchronous queues can be implemented using different synchronization primitives:



  • Pipes or sockets.
  • Queues protected by a mutex and a condition variable.
  • Non-blocking or blocked queues.
+3


source


The subject that you want to notify about an event of type "available data" can register a callback function that can be passed by the notification thread. You can use a function pointer for this.

Example: Thread 2 registers a callback function for one or more events. Topic 1 about the occurrence of a condition or event calls the registered function.

+1


source







All Articles