Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of struct objects - Thread safety

I have a global array of struct objects that is accessed by multiple threads concurrently. However there is a guarantee that the individual data members of the struct object(at a particular array index) accessed by two different threads at a time will always be different.

My question is whether I need to have a mutex lock on this global array for its access or not.

My struct looks like this:

struct data{
   string a;
   int b;
   uint16_t c;
};

EDIT:

I have a multithreaded UDP server program that creates a fixed number of threads and does recvfrom() block on the same global UDP socket. Whichever thread receives the datagram first, would process that datagram. In this situation, in order to facilitate the storage of client data, I have this global array of objects. In my case, the processing on the data members would happen in this order: string a, int b, uint16_t c. No two threads would access the same data member of the same object, because client won't send request for item b until it receives response for item a and the array is indexed by the client_number.

like image 527
sadagns Avatar asked Dec 20 '25 01:12

sadagns


2 Answers

Basically if there is a 100% guarentee that two different threads is not touching the same location in memory at the same time there should be no need for using mutex lock.

However if you are only 99.99% certain that it will not be touched the same time, you definitly need a mutex lock.

On the other hand, will the use of a mutex lock impact your application in any way? Because, if it isn't it might be worth adding a mutex for safety in case something isn't running exactly as you expect it to.

like image 108
Carsten Farving Avatar answered Dec 22 '25 14:12

Carsten Farving


However there is a guarantee that the individual data members of the struct object accessed by two different threads at a time will always be different.

How do you guarantee that if not by synchronizing your threads somehow?

If you mean that thread 'a' always only accesses member 'a' while thread 'b' always only accesses member 'b', then you won't need a lock or other synchronization.

Otherwise, you will need some synchronization. A mutex for the struct object would be one way to do it. The guarantee you mention could be given by having mutexes for the individual struct members or critical sections for code parts accessing one of them.

So, if you really can give this guarantee, no, you don't need another mutex. But that would imply you already have some synchronization in place.