7

I have a task to write multithreaded network chat for Linux, and I have got a question: how to I broadcast single message to every thread? I thought about either getting pipe for each thread in main thread, or getting single pipe for all threads. In my opinion second variant is better, but the problem is that you can't read same data from pipe multiple times and you can't lseek it.

So, the question is: is there any way to organize communication by file descriptor and read from it just like recv with MSG_PEEK does? Or am I following the wrong way?

dm33tri
  • 189
  • 9
  • You can write to buffer and synchronize the threads to read to from it. Unless all threads read `i-th` cell, you can't write to it. But this will require a much more complicated programming – Tony Tannous May 20 '17 at 22:11
  • You can "broadcast" by writing the data to a shared memory and signalling all the threads to read it. Signalling can be done with primitives such [condition variables](http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_cond_broadcast.html) – kaylum May 20 '17 at 22:19
  • 1
    Here is a handy list of [linux IPC mechanisms](http://www.chandrashekar.info/articles/linux-system-programming/introduction-to-linux-ipc-mechanims.html). Note that if you're using threads you have much more options since they see each other's data. Look at your threading library's primitives for synchronisation tools. – spectras May 20 '17 at 22:33
  • You wish to send a message to every other chzt clients on the network, so do a broadcast message. This thread shows how to send broadcast messages in `C`. [Answer](https://stackoverflow.com/questions/337422/how-to-udp-broadcast-with-c-in-linux) – Lavigne958 Mar 13 '22 at 08:29
  • You predicted correctly -- you are following the wrong path. One right path may be to have an intermediary distributor that replicates broadcast messages to all endpoints along with other services. There are more complicated ones with marginally better performance. – mevets Apr 02 '23 at 04:55

0 Answers0