Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inter thread data transfer - Linux

My program have two thread created from main thread. Each thread operates on seperate external communicating device connected.

                main thread
    thread_1                        thread_2

Thread_1 receives data packet from external device. Each data packet is an structure of 20 bytes each.

Now i want thread_2 to read data received by thread_1 & transfer it to device connected to it.

How can we transfer data between my two threads.

What exact name of the linux variables types to use in this case ?

like image 712
Allan Avatar asked Feb 18 '23 07:02

Allan


1 Answers

Your problem is a classic example of the Producer Consumer Problem.

There a number of possible ways to implement this depending on the context - your post is tagged with both pthreads, and linux-device-drivers. Is this kernel-space, user-space, or kernel-space -> userspace?

Kernel Space

A solution is likely to involve a ring buffer (if you anticipate that multiple messages between threads can be in flight at once) and a semaphore.

Chapter 5 of Linux Device Drivers 3rd Edition would be a good place to start.

User-space

If both threads are in user-space, the producer-consumer pattern in the same process is usually implemented with a pthread condition variable. An worked example of how to do it is here

Kernel-space -> User-space

The general approach used in Linux is for user-space thread thread_2 to block on a filing system object signalled by kernel-space thread_1. Typically the filing system object in question is in /dev or /sys. LDD3 has examples of both approaches.

like image 145
marko Avatar answered Apr 27 '23 20:04

marko