1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h>
pthread_rwlock_t rwlock;
void checkRes(char * funName, int ret) { if (ret) printf("Fun %s error %d\n", funName, ret); }
void *rdlockThread(void *arg) { int ret = 0;
printf("Entered thread, getting read lock\n"); ret = pthread_rwlock_rdlock(&rwlock); checkRes("pthread_rwlock_rdlock", ret); printf("got the rwlock read lock\n");
sleep(5);
printf("unlock the read lock\n"); ret = pthread_rwlock_unlock(&rwlock); checkRes("pthread_rwlock_unlock", ret); printf("thread read lock unlocked\n");
return NULL; }
void *wrlockThread(void *arg) { int ret = 0; printf("Entered thread, getting write lock\n"); ret = pthread_rwlock_wrlock(&rwlock); checkRes("pthread_rwlock_wrlock", ret);
printf("Got the rwlock write lock, now unlock\n"); ret = pthread_rwlock_unlock(&rwlock); checkRes("pthread_rwlock_unlock", ret); printf("thread write lock unlock\n");
return NULL; }
int main(int argc, char **argv) { int ret = 0; pthread_t pid_read, pid_write; printf("Enter Testcase - %s\n", argv[0]);
printf("Main, init the rwlock\n"); ret = pthread_rwlock_init(&rwlock, NULL); checkRes("pthread_rwlock_init\n", ret);
printf("Main grab a read lock\n"); ret = pthread_rwlock_rdlock(&rwlock); checkRes("pthread_rwlock_rdlock", ret);
printf("Main grab the same read lock again\n"); ret = pthread_rwlock_rdlock(&rwlock); checkRes("pthread_rwlock_rdlock", ret);
printf("Main create the read lock thread\n"); ret = pthread_create(&pid_read, NULL, rdlockThread, NULL); checkRes("pthread_create", ret);
printf("Mian unlock first read lock\n"); ret = pthread_rwlock_unlock(&rwlock); checkRes("pthread_rwlock_unlock", ret);
printf("Mian create the write lock thread\n"); ret = pthread_create(&pid_write, NULL, wrlockThread, NULL); checkRes("pthread_create", ret);
sleep(5);
printf("Main unlock the second read lock\n"); ret = pthread_rwlock_unlock(&rwlock); checkRes("pthread_rwlock_unlock", ret);
printf("Main wait for the threads\n"); ret = pthread_join(pid_read, NULL); ret |= pthread_join(pid_write, NULL); checkRes("pthread_join", ret);
ret = pthread_rwlock_destroy(&rwlock); checkRes("pthread_rwlock_destory", ret);
printf("end\n");
return 0;
}
|