Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I protect a character string in shared memory between two processes?

I have a piece of shared memory that contains a char string and an integer between two processes.

Process A writes to it and Process B reads it (and not vice versa)

What is the most efficient and effective way to make sure that Process A doesn't happen to update (write to it) that same time Process B is reading it? (Should I just use flags in the shared memory, use semaphores, critical section....)

If you could point me in the right direction, I would appreciate it.

Thanks.

Windows, C++

like image 371
T.T.T. Avatar asked Jun 27 '26 14:06

T.T.T.


1 Answers

You cannot use a Critical Section because these can only be used for synchronization between threads within the same process. For inter process synchronization you need to use a Mutex or a Semaphore. The difference between these two is that the former allows only a single thread to own a resource, while the latter can allow up to a maximum number (specified during creation) to own the resource simultaneously.

In your case a Mutex seems appropriate.

like image 121
Praetorian Avatar answered Jun 29 '26 07:06

Praetorian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!