I have two threads (I am using pthreads on GNU/Linux). Now they are sharing information using global variables (I know, it’s not nice). At the end of each cycle they have to send the value of 5 variables (doubles) to the other thread.
I would like to introduce a fixed time delay in their communication channel,
i.e.
thread1 (1kHz) <—> 10ms <—> thread2 (1kHz)
I was thinking that, at each cycle, I could create a thread which reads the value, sleep for 10ms, then forward it to the other thread and then dies.
This will make the system create 2 threads every cycle, one for each direction of the communication channel (2 threads per millisecond).
Is there any other intelligent way of simulating a delay in the communication?
UPDATE: I do not want to synchronize the communication of the threads but add a delay between them.
If thread1 writes something at time 1s the other thread should be able to read it only at time 1s + 10ms.
This doesn’t sound like a performance problem, so make it simple. No need for complex data structures, extra threads, etc.
Make a struct for your data, add a timestamp field to it.
Make an array to hold at least 10 of your structs. Go for 100 to be safe. Not going to use a lot of memory here, so who cares. Heck you could malloc it whenever it needed to grow.
Each thread has one such array, and a count of items in the array.
When a thread is ready to send data, do two things:
enough send that data to the other thread. After sending, decrement
the count and memmove the rest of the items in the array down one
notch.
current time stamp and increment the count.
Repeat for other thread.