Fstream在读取文件时给出空行,与pthreads一起使用



我正在尝试在文件读/写上实现读写器问题,而不仅仅是C++中的一个变量。为此,我声明了一个全局fstream变量,用于打开文件。以及两个功能,一个用于读者,一个用作作者。这是我的代码:

#include<pthread.h>
#include<semaphore.h>
#include<iostream>
#include<fstream>
using namespace std;
/// One writer, multiple readers

// initialize the file to be read and write 
fstream file("text.txt",ios::in|ios::out|ios::app);
// declare semaphore and mutex
sem_t rw_semaphore;
pthread_mutex_t multiread_mutex;
// variable to keep track of number of readers
int readers = 0;
void *writer(void *arg){
// try to get the semaphore for accessing the file
sem_wait(&rw_semaphore);
// write to the file
file << "Wrote to the file.."<<*(int *)arg<<endl;
cout<<"Writer no. "<<*(int *)arg<<" wrote to the file"<<endl;
// signal realease of semaphore for accessing the file
sem_post(&rw_semaphore);
}
void *reader(void *arg){
// Lock mutex for accessing readers count variable
pthread_mutex_lock(&multiread_mutex);
readers++;
// if this is the first reader, try to get the semaphore
if(readers == 1){
sem_wait(&rw_semaphore);
}
// release mutex lock
pthread_mutex_unlock(&multiread_mutex);
// read the file
cout<<"Reader no: "<<*(int *)arg<<" reading file: -"<<endl;
for(string line;getline(file,line);){
cout<<line<<endl;
}
file.clear();
// lock mutex
pthread_mutex_lock(&multiread_mutex);
readers--;
// if this is the last reader, release the semaphore
if(readers == 0){
sem_post(&rw_semaphore);
}
// release mutex lock
pthread_mutex_unlock(&multiread_mutex);
}
int main()
{
pthread_t read[7], write[5];
pthread_mutex_init(&multiread_mutex,NULL);
sem_init(&rw_semaphore,0,1);
int *arg = new int;
for(int i=0;i<7;i++){
*arg = i+1;
pthread_create(&read[i],NULL,reader,(void *)arg);
}
for(int i=0;i<5;i++){
*arg = i+1;
pthread_create(&write[i],NULL,writer,(void *)arg);
}
for(int i=0;i<7;i++){
pthread_join(read[i],NULL);
}
for(int i=0;i<5;i++){
pthread_join(write[i],NULL);
}
pthread_mutex_destroy(&multiread_mutex);
sem_destroy(&rw_semaphore);
file.close();
return 0;
}

但是cout打印文件中的行并没有打印任何内容。这是我得到的输出:

Reader no: 2 reading file: -
Reader no: 3 reading file: -
Reader no: 4 reading file: -
Reader no: 5 reading file: -
Reader no: 6 reading file: -
Reader no: 7 reading file: -
Reader no: 1 reading file: -
Writer no. 2 wrote to the file
Writer no. 3 wrote to the file
Writer no. 3 wrote to the file

写入程序正在对文件进行写入,并且在读取时文件不是空的。我做错了什么?

读卡器的同步不足。不能让多个读卡器同时从同一个iostream对象中读取内容。

此外,@Basya已经暗示,你对自己在文件中的位置有一个误解。你在那个文件中只有一个索引,你可以通过读写来不断推进。它最初也位于文件的末尾。

当您像管道一样使用文件时,您应该打开它进行独立的读写。当在Windows或Cygwin上运行此程序时,您当然必须稍微超越STL fstream,才能获得下面的非独占文件句柄。

你的排序也有点错误。正如输出所示,你的读者领先于作者。信号量和互斥的错误使用。您应该使用互斥锁来保护file,而使用信号量作为已完成写入次数的计数器。仅从写入程序递增,仅从读取器等待。当然,届时会有两名读者挨饿,但在所有作者加入后,你通常会有一个单独的停止条件来跟踪这一情况。(为了在设置停止条件后唤醒读取器,您可以从主线程再次增加信号量。(

还有一条经验法则:当你持有互斥对象时,不要等待信号量,这会让一切倒退。条件变量就不同了,因为它有在互斥体所有权和等待CV之间切换的原子操作,但对于信号量来说,这表明你的用法错误。

最新更新