reader_writer1.c:
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <semaphore.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <signal.h>
- #include <errno.h>
- #define SIZE 1000 // the size of the buffer
- #define SECS 10 // the time to run
- pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
- sem_t sem_empty, sem_full;
- long buffer[SIZE] = {0};
- // record the times to meet lock
- int read_lock_times = 0;
- int write_lock_times = 0;
- // record the times of reading or writing
- int read_num = 0;
- int write_num = 0;
- // signal handler
- void sig_handler(int sig_num)
- {
- printf("Meet %d read locks\n", read_lock_times);
- printf("Meet %d write locks\n", write_lock_times);
- printf("Read %d numbers\n", read_num);
- printf("Write %d numbers\n", write_num);
- exit(0);
- }
- void * read_thread(void * args)
- {
- while(1)
- {
- sem_wait(&sem_empty);
- if( pthread_mutex_trylock(&mut) == EBUSY)
- {
- ++ read_lock_times;
- pthread_mutex_lock(&mut);
- }
- ++ read_num;
- pthread_mutex_unlock(&mut);
- sem_post(&sem_full);
- }
- }
- void * write_thread(void * args)
- {
- while(1)
- {
- sem_wait(&sem_full);
- if( pthread_mutex_trylock(&mut) == EBUSY)
- {
- ++ write_lock_times;
- pthread_mutex_lock(&mut);
- }
- buffer[write_num%SIZE] = write_num;
- ++write_num;
- pthread_mutex_unlock(&mut);
- sem_post(&sem_empty);
- }
- }
- int main()
- {
- // install the signal handler
- struct sigaction action;
- action.sa_handler = sig_handler;
- sigaction(SIGALRM, &action, NULL);
- alarm(SECS);
- sem_init(&sem_empty, 0, 0);
- sem_init(&sem_full, 0, SIZE);
- pthread_t tid1, tid2;
- pthread_create(&tid1, NULL, read_thread, NULL);
- pthread_create(&tid2, NULL, write_thread, NULL);
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- sem_destroy(&sem_empty);
- sem_destroy(&sem_full);
- pthread_mutex_destroy(&mut);
- return 0;
- }
背景无需多说。
上述代码假定缓冲池容量固定,大小由 SIZE 控制。
在 SECS 秒后,会输出 读线程、写线程 遇到的锁的个数,以及 读写的数目。
以下是上面程序的输出:
/home/adamas:~$ time ./read_writer1
Meet 1 read locks
Meet 0 write locks
Read 1137205 numbers
Write 1137794 numbers
real 0m10.017s
user 0m4.252s
sys 0m5.640s
显然,这里的输出数目与 SIZE 密切相关,并不是越大越好,SIZE 定义为 10,000,反而不如定义为 1,000 快。
下一篇中谈谈使用 C++ 中的 vector 来代替本文中的 固定容量数组。
阅读(2479) | 评论(0) | 转发(0) |