UNIX环境高级编程:线程同步之读写锁及属性
运行结果: huangcheng@ubuntu:~$ gcc 2.c -lpthread huangcheng@ubuntu:~$ ./a.out 5 3 pthread_rwlock_wrlock: Success pthread_rwlock_rdlock: Success Writers begings write message. Enter the write message: hu pthread_rwlock_wrlock: Success pthread_rwlock_rdlock: Success Writers begings write message. Enter the write message: 1 pthread_rwlock_wrlock: Success pthread_rwlock_rdlock: Success Writers begings write message. Enter the write message: 2 pthread_rwlock_rdlock OK Reader begins read message. Read message is: hu12 pthread_rwlock_unlock fail pthread_rwlock_rdlock OK Reader begins read message. Read message is: hu12 pthread_rwlock_unlock fail pthread_rwlock_rdlock OK Reader begins read message. Read message is: hu12 pthread_rwlock_unlock fail pthread_rwlock_rdlock OK Reader begins read message. Read message is: hu12 pthread_rwlock_unlock fail pthread_rwlock_rdlock OK Reader begins read message. Read message is: hu12 pthread_rwlock_unlock fail 结果说明: (1)当一个线程获得读写锁的写模式,其他线程试图获得该读写锁的读模式或者是写模式,都将会阻塞,直到该线程释放该读写锁。 3读写锁的属性设置 /* 初始化读写锁属性对象 */ int pthread_rwlockattr_init (pthread_rwlockattr_t *attr); /* 销毁读写锁属性对象 */ int pthread_rwlockattr_destroy (pthread_rwlockattr_t *attr); /* 获取读写锁属性对象在进程间共享与否的标识*/ int pthread_rwlockattr_getpshared (__const pthread_rwlockattr_t *attr,int *pshared); /* 设置读写锁属性对象,标识在进程间共享与否 */ int pthread_rwlockattr_setpshared (pthread_rwlockattr_t *attr, int pshared); 返回值:成功返回0,否则返回错误代码 pthread_rwlockattr_setpshared()函数的第二个参数pshared用于设定是否进程间共享,其值可以是PTHREAD_PROCESS_PRIVATE或PTHREAD_PROCESS_SHARED,后者是设置进程间共享。 查看本栏目更多精彩内容:http://www.bianceng.cn/OS/unix/ 示例代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <errno.h> struct{ pthread_rwlock_t rwlock; int product; }sharedData = {PTHREAD_RWLOCK_INITIALIZER, 0}; void * produce(void *ptr) { int i; for ( i = 0; i < 5; ++i) { pthread_rwlock_wrlock(&sharedData.rwlock); sharedData.product = i; printf("produce:%dn",i); pthread_rwlock_unlock(&sharedData.rwlock); sleep(1); } } void * consume1(void *ptr) { int i; for ( i = 0; i < 5;) { pthread_rwlock_rdlock(&sharedData.rwlock); printf("consume1:%dn",sharedData.product); pthread_rwlock_unlock(&sharedData.rwlock); ++i; sleep(1); } } void * consume2(void *ptr) { int i; for ( i = 0; i < 5;) { pthread_rwlock_rdlock(&sharedData.rwlock); printf("consume2:%dn",sharedData.product); pthread_rwlock_unlock(&sharedData.rwlock); ++i; sleep(1); } } int main() { pthread_t tid1, tid2, tid3; pthread_create(&tid1, NULL, produce, NULL); pthread_create(&tid2, NULL, consume1, NULL); pthread_create(&tid3, NULL, consume2, NULL); void *retVal; pthread_join(tid1, &retVal); pthread_join(tid2, &retVal); pthread_join(tid3, &retVal); return 0; } (编辑:应用网_丽江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |