最近在完善自己的个人小网站,以前写小玩具/算法题不会用到文件I/O流,这次升级小网站需要用到json文件,当时在想FILE是不是线程安全的?如果一个线程用完这个资源,但是这个线程是阻塞在这里的,那么这个资源会被释放吗?答案是,会被释放,操作系统会帮我们做这些事情的.当持有资源使用完毕会释放持有的资源,而且也是线程安全的,只不过不加锁无法保证写入文件的顺序.
#include <stdio.h>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include <string.h>
using namespace std;
FILE* fp = nullptr;
void write(string s){
fwrite(s.c_str(),s.size(),1,fp);
//fflush(fp);
}
void read(){
char buff[1024];
fread(buff,1024,1,fp);
char* buf = "i come here\n";
fwrite(buf,strlen(buf),1,fp);
// fflush(fp);
// 读占用这个资源,看看写操作可不可以用fp
sleep(10);
}
// 这跟线程去读
void thread1(){
read();
}
int main(){
fp = fopen("./1.txt","r+");
thread t1(thread1);
// 主线程去写,保证先读
sleep(2);
write("hello ");
write("world!\n");
write("dxgzg ");
write("and cy\n");
write("========\n");
t1.join();
fclose(fp);
return 0;
}
那如果两个FILE指针,线程安全吗?怎么说呢?fp内部会记录每个指针读到的位置,然后在当前读到的后面在添加数据.比如fp1读到的偏移量是0,直接在头上就加数据,这时候fp2读到的也是0,因为是两个指针,fp2也从头上加了,加锁也解决不了这个问题的.因为是操作系统缓冲区给加进去的.与谁先执行是没有关系的.
#include <stdio.h>
#include <iostream>
#include <string>
#include <thread>
#include <unistd.h>
#include <string.h>
#include <mutex>
using namespace std;
FILE* fp1 = nullptr;
FILE* fp2 = nullptr;
mutex g_mutex;
void write(string s){
std::unique_lock<mutex> lock(g_mutex);
fwrite(s.c_str(),s.size(),1,fp1);
fflush(fp1);
}
void read(){
std::unique_lock<mutex> lock(g_mutex);
char buff[1024];
fread(buff,1024,1,fp2);
char* buf = "i come here\n";
fwrite(buf,strlen(buf),1,fp2);
fflush(fp2);
lock.unlock();
// 读占用这个资源,看看写操作可不可以用fp
sleep(10);
}
// 这跟线程去读
void thread1(){
read();
}
int main(){
fp1 = fopen("./1.txt","r+");
fp2 = fopen("./1.txt","r+");
thread t1(thread1);
// 主线程去写,保证先读
sleep(2);
write("hello ");
write("world!\n");
write("dxgzg ");
write("and cy\n");
write("========\n");
t1.join();
fclose(fp1);
fclose(fp2);
return 0;
}