1/* 2 * Copyright (c) 2002, Intel Corporation. All rights reserved. 3 * This file is licensed under the GPL license. For the full content 4 * of this license, see the COPYING file at the top level of this 5 * source tree. 6 * 7 * Test pthread_rwlock_init(). 8 * 9 * If attr is NULL, the default read-write lock attributes shall be used; 10 * the effect is the same as passing the address of a default read-write 11 * lock attributes object. 12 * 13 * Steps: 14 * 1. Initialize a pthread_rwlock_t object 'rwlock' with pthread_rwlock_init(), 15 * set 'attr' as NULL. 16 * 2. Create a child thread, the thread lock 'rwlock' for reading, shall not block. 17 */ 18#define _XOPEN_SOURCE 600 19#include <pthread.h> 20#include <stdio.h> 21#include <stdlib.h> 22#include <unistd.h> 23#include <errno.h> 24#include "posixtest.h" 25 26static pthread_rwlock_t rwlock; 27static int thread_state; 28 29static void *fn_rd(void *arg) 30{ 31 32 thread_state = 2; 33 int rc; 34 35 printf("child: lock for reading\n"); 36 rc = pthread_rwlock_rdlock(&rwlock); 37 if (rc == 0) { 38 printf("child: get read lock\n"); 39 printf("child: unlock\n"); 40 if (pthread_rwlock_unlock(&rwlock) != 0) { 41 printf("child: release read lock\n"); 42 exit(PTS_UNRESOLVED); 43 } 44 } else { 45 printf("Error in pthread_rwlock_rdlock().\n"); 46 exit(PTS_FAIL); 47 } 48 49 thread_state = 3; 50 pthread_exit(0); 51 return NULL; 52} 53 54int main(void) 55{ 56 int cnt = 0; 57 int rc = 0; 58 59 pthread_t thread; 60 61 rc = pthread_rwlock_init(&rwlock, NULL); 62 if (rc != 0) { 63 printf 64 ("Test FAILED: Error at pthread_rwlock_init(), returns %d\n", 65 rc); 66 return PTS_FAIL; 67 } 68 69 thread_state = 1; 70 printf("main: create thread\n"); 71 if (pthread_create(&thread, NULL, fn_rd, NULL) != 0) { 72 printf("main: failed to create thread\n"); 73 return PTS_UNRESOLVED; 74 } 75 76 /* If the shared data is not altered by child after 3 seconds, 77 we regard it as blocked */ 78 /* We expect the thread not to block */ 79 cnt = 0; 80 do { 81 sleep(1); 82 } while (thread_state != 3 && cnt++ < 3); 83 84 if (thread_state == 2) { 85 printf("Test FAILED: thread blocked on read lock\n"); 86 exit(PTS_FAIL); 87 } else if (thread_state != 3) { 88 printf("main: Unexpected thread state\n"); 89 exit(PTS_UNRESOLVED); 90 } 91 92 if (pthread_join(thread, NULL) != 0) { 93 printf("main: Error at pthread_join()\n"); 94 exit(PTS_UNRESOLVED); 95 } 96 97 if (pthread_rwlock_destroy(&rwlock) != 0) { 98 printf("Error at pthread_rwlock_destroy()\n"); 99 return PTS_UNRESOLVED; 100 } 101 102 printf("Test PASSED\n"); 103 return PTS_PASS; 104} 105