3

I am writing a program in which a memory array is modified by one thread under 2 possible operations (modify the array content, or dealloc the array and replace it by allocating a new array). The memory array can be read by many threads except when the array is modified or deallocated and replaced.

I know how to use mutex lock to allow the memory to be modified by only one thread at all time. How can I use it (or other multithreading tools in c) to allow arbitrary number of read threads to access the memory, except when the write thread modifies the memory?

Pippi
  • 2,451
  • 8
  • 39
  • 59
  • 2
    You may be interested in `pthread_rwlock_init`, `pthread_rwlock_wrlock` and `pthread_rwlock_rdlock`. – user3386109 May 07 '16 at 02:30
  • http://www.unix.com/man-page/netbsd/3/pthread_rwlock/ – xvan May 07 '16 at 02:34
  • Thx! where can I find a good tutorial / examples of using repthread_rwlock_wrlock? – Pippi May 07 '16 at 02:42
  • using a semaphore comes to mind .. they can be used to throttle thread access to a data structure (ie, you have a pool of worker threads, but you only want 5 of them at a time operating on a data structure). – yano May 07 '16 at 03:11
  • Define "best". Without clear goals, your question is meaningless. – Ulrich Eckhardt May 07 '16 at 07:03

1 Answers1

2

The best solution to achieve this is using read-write locks i.e pthread_rwlock_* as already answered in above comments. Providing a little more detail about it.

Read-write locks are used for shared read access or exclusive write access. A thread that needs read access can't continue while any thread currently has write access. A thread that needs write access can't continue when any other thread has either write access or read access. When both readers and writers are waiting for the access at the same time, there is default action to give precedence to any of them, this rule can be changed.

Read-write lock functions with arguments are much clearly explained here: https://docs.oracle.com/cd/E19455-01/806-5257/6je9h032u/index.html

There is a post in stackoverflow itself about the same: concurrent readers and mutually excluding writers in C using pthreads

This (read-write locks) may cause the writer thread to starve if precedence are not properly defined and implementation has not taken care of case when too many readers are waiting for writer to finish. So read about it too: How to prevent writer starvation in a read write lock in pthreads

Community
  • 1
  • 1