学一学I/O,是否线程安全,不再使用资源是否会阻塞资源?

最近在完善自己的个人小网站,以前写小玩具/算法题不会用到文件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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值