| 
  
读者写者问题
  
 
这也是一个非常经典的多线程题目,题目大意如下:有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件,同样有读者读时写者也不能写。
  
 
程序:
  
 
  
 
// reader_writer.cpp 
////////////////////////////////////////////////////////////////////// 
// 读者写者问题 
// 有一个写者很多读者,多个读者可以同时读文件,但写者在写文件时不允许有读者在读文件, 
// 同样有读者读时写者也不能写。 
////////////////////////////////////////////////////////////////////// 
#include <pthread.h> 
#include <stdio.h> 
#include <unistd.h> 
// 定义数据类 
class data 
{ 
public: 
data(int i, float f): 
I(i), F(f) 
{} 
int I; 
float F; 
}; 
// 读者写者读写的内容 
data *p_data = NULL; 
pthread_rwlock_t lock; 
// 写者数目 
const int WRITER_NUMBER = 2; 
void *reader(void *arg); 
void *writer(void *arg); 
int main(int argc, char **argv) 
{ 
pthread_t reader_tid; 
pthread_t writer_tid[WRITER_NUMBER]; 
pthread_create(&reader_tid, NULL, reader, NULL); 
for (int i = 0; i < WRITER_NUMBER; ++i) 
{ 
pthread_create(&writer_tid, NULL, writer, (void *)i); 
} 
sleep(1); 
return 0; 
} 
void *reader(void *arg) 
{ 
int id = (int)arg; 
pthread_detach(pthread_self()); 
while (true) 
{ 
pthread_rwlock_rdlock(&lock); 
printf("reader %d is reading the data; ", id); 
if (p_data == NULL) 
{ 
printf("the data is NULL\n"); 
} 
else 
{ 
printf("the data is (%d, %f)\n", p_data->I, p_data->F); 
} 
pthread_rwlock_unlock(&lock); 
} 
return (void *)0; 
} 
void *writer(void *arg) 
{ 
pthread_detach(pthread_self()); 
while (true) 
{ 
pthread_rwlock_wrlock(&lock); 
printf("writer is writing the data; "); 
if (p_data == NULL) 
{ 
p_data = new data(1, 1.1f); 
printf("writer create the data (%d, %f)\n", p_data->I, p_data->F); 
} 
else 
{ 
delete p_data; 
p_data = NULL; 
printf("writer free the data\n"); 
} 
pthread_rwlock_unlock(&lock); 
} 
return (void *)0; 
} |