0

Multiple user space processes could access this value at the same time so I guess we should use some locks or memory barrier things for safe but I could find quite a lot code in linux driver who doesn't, or just protect the write case. Do we really need a mutex for both read case and write case?

Adrian Hu
  • 3
  • 1
  • Are you using shm ? (Shared Memory Segment) – rak007 Sep 21 '17 at 09:51
  • Not really. My case is, for example, I have a rw register "REG", and in driver I cached it's value with "int reg", then I create a sysfs file, let's say, "/sys/.../reg". When user echo an int value to "/sys/.../reg", this value will be written to REG, and cached to "int reg"; When user cat "/sys/.../reg", driver will just give "int reg" to user. My question is, do I need add a mutex to protect "int reg" for both echo and cat case? – Adrian Hu Sep 21 '17 at 09:59
  • If you are writing in files with multiple process / threads, maybe this post could help you : https://stackoverflow.com/questions/26565498/multiple-threads-writing-on-same-file – rak007 Sep 21 '17 at 10:02
  • 1
    Does it really make sense to talk about the fread/fwrite here? What if people use read/write system call directly? Also, I think there is some different between regular file system and sysfs. – Adrian Hu Sep 21 '17 at 10:23

1 Answers1

1

It depends on the CPU and the system that the code is executed. Actually you can do this without synchronization techniques if the operation is atomic. As long as you're not sure about this it's better to use a synchronization object. For int/dword values most of the time people do this without sych object.

Read this article http://preshing.com/20130618/atomic-vs-non-atomic-operations/

and also a same issue Are C++ Reads and Writes of an int Atomic?

EWD-0-
  • 113
  • 9