Created
July 13, 2020 14:01
-
-
Save swilly22/058289db5a7a20ec4922e8e9b67ef57f to your computer and use it in GitHub Desktop.
reentrant read lock when writer is trying to acquire lock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
#include <unistd.h> | |
pthread_rwlock_t rwlock; | |
void* writer(void *arg) { | |
printf("in writer thread, trying to acquire write lock\n"); | |
pthread_rwlock_wrlock(&rwlock); | |
printf("acquired write lock\n"); | |
return NULL; | |
} | |
int main (int argc, char **argv) { | |
// create RWLock | |
assert(pthread_rwlock_init(&rwlock, NULL) == 0); | |
// acquire read lock | |
pthread_rwlock_rdlock(&rwlock); | |
printf("read lock acquired\n"); | |
// reentrant with read | |
printf("about to re-acquire read lock\n"); | |
pthread_rwlock_rdlock(&rwlock); | |
printf("reentrant read lock\n"); | |
// create writer thread | |
pthread_t thread; | |
assert(pthread_create(&thread, NULL, writer, NULL) == 0); | |
// wait for writer to try and acquire write lock | |
sleep(1); | |
// third reentrant with read | |
printf("about to re-acquire read lock for the third time\n"); | |
pthread_rwlock_rdlock(&rwlock); | |
printf("reentrant read lock\n"); | |
// clean up | |
assert(pthread_rwlock_destroy(&rwlock) == 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment