Execute parallel tasks with shared information in C

Let‘s say I‘m building a program that accepts client connections, puts every new client into a list, prints the list to the console and updates whenever a new client connects.

At the same time (so while accept() is blocking the program flow; a client connects with a socket), I want to handle user input. The user shall always be able to choose a specific client from the list to communicate with by typing a number to the console (let’s assume that each client corresponds to a unique number (id)).

How can I achieve this in C? Should I use processes and exchange information by using shared memory or sockets or should I prefer threads? And why?

Although the title of my question is a little vague, this question is not a duplicate as I am asking for a method to use for this specific example.

1 answer

  • answered 2018-10-11 22:37 Bwebb

    How can I achieve this in C? Should I use processes and exchange information by using shared memory or sockets or should I prefer threads? And why?

    Prefer threads because they are easier to work with. Use mutex for data shared between threads, use pthread or winthread depending on your OS. This will get you a working prototype as fast as possible.

    Anything besides a working prototype can't really be assessed with the information you have provided. How many clients, what OS, is the client list in RAM or on a disk (probably depends on client size), etc...? Most things have trade-offs.