reader_writer2.c:
- #include <iostream>
- #include <vector>
- #include <pthread.h>
- #include <unistd.h>
- #include <errno.h>
- #include <signal.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #define SIZE 1000
- #define SECS 10
- using namespace std;
- vector<int> vec(SIZE);
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- sem_t sem_empty, sem_full;
- // 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;
- 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(&mutex) == EBUSY)
- {
- ++ read_lock_times;
- pthread_mutex_lock(&mutex);
- }
- if(vec.size() > 0)
- {
- vec.erase(vec.begin());
- ++ read_num;
- }
- pthread_mutex_unlock(&mutex);
- sem_post(&sem_full);
- }
- }
- void * write_thread(void * args)
- {
- while(1)
- {
- sem_wait(&sem_full);
- if( pthread_mutex_trylock(&mutex) == EBUSY)
- {
- ++ write_lock_times;
- pthread_mutex_lock(&mutex);
- }
- vec.push_back(write_num);
- ++write_num;
- pthread_mutex_unlock(&mutex);
- 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);
- }
改动不大,就是把原来固定容量的数组改为了容量可变的 STL 容器 vector.
注意这里的 semaphore 同步机制是必须的,否则会因为写线程写的太快导致内存不够,std::bad_alloc.
命令 time ./reader_writer2 运行结果如下:
Meet 0 read locks
Meet 9 write locks
Read 316228 numbers
Write 317227 numbers
real 0m10.017s
user 0m0.764s
sys 0m8.709s
显然,速度比固定容量的数组慢了很多,差别应该是在 vector 的操作上,需要调整内存,维护成员指针等等。
如果只有一个线程执行读写操作(先读后写), 则 10 秒钟内可以读写 2000 多万次,多线程后性能只有原来的 15%.
阅读(2373) | 评论(0) | 转发(0) |