I'm working in a mingw program with two threads (pthread_t) in addition to the main execution. Each thread contains an endless loop for continuous communication with an external instrument, each communication having different speed and protocol. Main program is just displaying instrument data at run time, upon user request. The endless loops in the threads will only exit when a "keepalive" variable is set to 0 in main. To exchange data between threads, I would like to know the pros and cons of the two ways that I know:
passing arguments to the thread (a structure can be passed using the last argument of pthread_create: *arg).
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
using global variables and controlling the concurrency (pthread_mutex_lock and pthread_mutex_unlock)
Actually I'm using both ways (mainly because I needed an early "working program version"). As an example of the variable exchanges I'm refering to:
- I'm defining the "keepalive" variable as global (to share it when the threads enter the endless loop).
- I'm passing the communication configuration data by means of the struct.
- I'm retrieving the instrument data to main by means of a global array (updated within the endless loops)
- I'm retrieving the handles to files and communication with the struct (at the end, to close and free everything properly).
I would appreciate some advice on drawbacks about using global variables versus using the struct with atomic variables. (Code cleanliness, speed, efficiency, cpu/memory usage...).
Thanks.