reader/writer lock in pthread

前端 未结 1 1638
旧时难觅i
旧时难觅i 2020-12-29 16:35

I\'m learning pthread and came across reader writer lock. The scenario is very simple; a global variable being shared by all the threads, reader keeps printing the current v

相关标签:
1条回答
  • 2020-12-29 16:47

    When a thread acquires a lock, other threads trying to acquire the same lock will be suspended until the first thread releases the lock.

    What is happening here is that your reader thread starts, acquires the lock, and enters the for/poll loop.

    The writer thread starts, tries to acquire the lock which was already taken by the reader thread, and remains blocked on pthread_rwlock_wrlock.

    What you actually want to do is to put your lock/unlock right before and after the code where you access your shared variable.

    thread_rwlock_rdlock(p);
    newx = ACCESS_ONCE(x);
    thread_rwlock_unlock(p);
    ...
    thread_rwlock_wrlock(p);
    ACCESS_ONCE(x)++;
    thread_rwlock_unlock(p);
    
    0 讨论(0)
提交回复
热议问题