dev/c/pthread_ex/pthread_rwlock_ex.c

95 lines
2.3 KiB
C
Raw Normal View History

#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
//#include "check.h"
void checkResults(const char *s, int rc)
{
}
2011-05-02 12:42:42 +04:00
pthread_rwlock_t rwlock;
void *rdlockThread(void *arg)
{
2011-05-02 12:42:42 +04:00
int rc;
2011-05-02 12:42:42 +04:00
printf("Entered thread, getting read lock\n");
rc = pthread_rwlock_rdlock(&rwlock);
checkResults("pthread_rwlock_rdlock()\n", rc);
printf("got the rwlock read lock\n");
2011-05-02 12:42:42 +04:00
sleep(5);
2011-05-02 12:42:42 +04:00
printf("unlock the read lock\n");
rc = pthread_rwlock_unlock(&rwlock);
checkResults("pthread_rwlock_unlock()\n", rc);
printf("Secondary thread unlocked\n");
return NULL;
}
void *wrlockThread(void *arg)
{
2011-05-02 12:42:42 +04:00
int rc;
2011-05-02 12:42:42 +04:00
printf("Entered thread, getting write lock\n");
rc = pthread_rwlock_wrlock(&rwlock);
checkResults("pthread_rwlock_wrlock()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Got the rwlock write lock, now unlock\n");
rc = pthread_rwlock_unlock(&rwlock);
checkResults("pthread_rwlock_unlock()\n", rc);
printf("Secondary thread unlocked\n");
return NULL;
}
int main(int argc, char **argv)
{
2011-05-02 12:42:42 +04:00
int rc = 0;
pthread_t thread, thread1;
2011-05-02 12:42:42 +04:00
printf("Enter Testcase - %s\n", argv[0]);
2011-05-02 12:42:42 +04:00
printf("Main, initialize the read write lock\n");
rc = pthread_rwlock_init(&rwlock, NULL);
checkResults("pthread_rwlock_init()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main, grab a read lock\n");
rc = pthread_rwlock_rdlock(&rwlock);
checkResults("pthread_rwlock_rdlock()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main, grab the same read lock again\n");
rc = pthread_rwlock_rdlock(&rwlock);
checkResults("pthread_rwlock_rdlock() second\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main, create the read lock thread\n");
rc = pthread_create(&thread, NULL, rdlockThread, NULL);
checkResults("pthread_create\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main - unlock the first read lock\n");
rc = pthread_rwlock_unlock(&rwlock);
checkResults("pthread_rwlock_unlock()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main, create the write lock thread\n");
rc = pthread_create(&thread1, NULL, wrlockThread, NULL);
checkResults("pthread_create\n", rc);
2011-05-02 12:42:42 +04:00
sleep(5);
printf("Main - unlock the second read lock\n");
rc = pthread_rwlock_unlock(&rwlock);
checkResults("pthread_rwlock_unlock()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main, wait for the threads\n");
rc = pthread_join(thread, NULL);
checkResults("pthread_join\n", rc);
2011-05-02 12:42:42 +04:00
rc = pthread_join(thread1, NULL);
checkResults("pthread_join\n", rc);
2011-05-02 12:42:42 +04:00
rc = pthread_rwlock_destroy(&rwlock);
checkResults("pthread_rwlock_destroy()\n", rc);
2011-05-02 12:42:42 +04:00
printf("Main completed\n");
return 0;
}