Linux--多线程读写锁问题

来源:互联网 发布:中研世纪 知乎 编辑:程序博客网 时间:2024/05/24 03:44

下面的案例是多个线程访问一个公共缓冲的处理,采用读写锁。需要注意的是代码中注释的地方。起初是将sleep放在unlock之前,这样的问题是,每次读线程读取完之后就直接睡眠导致写线程得到不到锁。由于写线程的写锁是独占的,需要保证读写锁没有被其他线程占用。


#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <string.h>#include <time.h>pthread_rwlock_t rwlock;char *contents = NULL;void *worker(void *arg){char *worker_name = (char *)arg;while(1){pthread_rwlock_rdlock(&rwlock);printf("%s need to work, time[%s]\n", worker_name, contents);//这里需要注意---------------------pthread_rwlock_unlock(&rwlock);sleep(1);}return (void *)0;}void *timer(void *arg){while(1){time_t tt = time(NULL);pthread_rwlock_wrlock(&rwlock);memset(contents, 0x0, 64 * sizeof(char));ctime_r(&tt, contents);if (contents[strlen(contents) -1] == '\n'){contents[strlen(contents) -1] = 0;}pthread_rwlock_unlock(&rwlock);}pthread_exit((void *)0);}int main(){pthread_t rd_th1, rd_th2, rd_th3;pthread_t wr_th1;contents = (char *)malloc(64 * sizeof(char));if (!contents){printf("malloc error\n");return -1;}memset(contents, 0x0, 64 * sizeof(char));pthread_rwlock_init(&rwlock, NULL);pthread_create(&rd_th1, NULL, worker, (void *)"lily");pthread_create(&rd_th2, NULL, worker, (void *)"hanmeimei");pthread_create(&rd_th3, NULL, worker, (void *)"lucy");pthread_create(&wr_th1, NULL, timer, NULL);pthread_join(rd_th1, NULL);pthread_join(rd_th2, NULL);pthread_join(rd_th3, NULL);pthread_join(wr_th1, NULL);pthread_rwlock_destroy(&rwlock);return 0;}


0 0
原创粉丝点击