Could you help me to understand how to use mutexes in multithread Linux application, where:
- during data writing it is need to lock variable on write and read
- during data reading from the variable it is need to lock it on write.
So it is possible to read simultaneously, but writing opertion is a single opertaion in the same time. During writing, all other operation should wait before it finishes.
You’re asking about something that is a bit higher level than mutexes. A mutex is a simple, low-level device. When you lock a thread with a mutex, the CPU is either executing code in the thread that obtained the lock or it is executing some other process entirely. In other words, the mutex has locked out all other threads that belong to the same (heavyweight) process.
You are asking about a read-write lock. Read-write locks use mutexes underneath the hood. The POSIX functions that deal with read-write locks start with
pthread_rwlock_. Since you are on a Linux machine, just typeman pthreadand look for the section marked “READ/WRITE LOCK ROUTINES”.