Linux多執行緒──讀者寫者問題
阿新 • • 發佈:2019-01-01
讀者寫者問題也是一個非常經典的多執行緒題目,題目大意如下:有一個寫者很多讀者,多個讀者可以同時讀檔案,但寫者在寫檔案時不允許有讀者在讀檔案,同樣有讀者讀時寫者也不能寫。
程式:
- // reader_writer.cpp
- //////////////////////////////////////////////////////////////////////
- // 讀者寫者問題
- // 有一個寫者很多讀者,多個讀者可以同時讀檔案,但寫者在寫檔案時不允許有讀者在讀檔案,
- // 同樣有讀者讀時寫者也不能寫。
- //////////////////////////////////////////////////////////////////////
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- // 定義資料類
- class data
- {
- public:
-
data(int
- I(i), F(f)
- {}
- int I;
- float F;
- };
- // 讀者寫者讀寫的內容
- data *p_data = NULL;
- pthread_rwlock_t lock;
- // 寫者數目
- constint 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[i], 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;
- }