栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

Linux多线程对同一文件读写

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Linux多线程对同一文件读写

FREAD(3)                        Linux Programmer's Manual                       FREAD(3)

NAME
       fread, fwrite - binary stream input/output

SYNOPSIS
       #include 

       size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

       size_t fwrite(const void *ptr, size_t size, size_t nmemb,
                     FILE *stream);

DEscriptION
       The function fread() reads nmemb elements of data, each size bytes long, from the
       stream pointed to by stream, storing them at the location given by ptr.

       The function fwrite() writes nmemb elements of data, each size bytes long, to the
       stream pointed to by stream, obtaining them from the location given by ptr.

       For nonlocking counterparts, see unlocked_stdio(3).

RETURN VALUE
       On  success,  fread()  and  fwrite()  return the number of items read or written.
       This number equals the number of bytes transferred only when size is  1.   If  an
       error occurs, or the end of the file is reached, the return value is a short item
       count (or zero).

       fread() does not distinguish between end-of-file and error, and callers must  use
       feof(3) and ferror(3) to determine which occurred.

ATTRIBUTES
       For an explanation of the terms used in this section, see attributes(7).

       ┌──────────────────┬───────────────┬─────────┐
       │Interface         │ Attribute     │ Value   │
       ├──────────────────┼───────────────┼─────────┤
       │fread(), fwrite() │ Thread safety │ MT-Safe │
       └──────────────────┴───────────────┴─────────┘

参考文档说明fread和fwrite是线程安全的,但是也会受操作系统和gnu libc实现的影响,需要根据实际情况进行测试。

同时多线程对同一文件进行读写的情况下,需要注意中间更新的情况:

例如:

1. 文件里有个整数100

2. 线程A读取文件中的整数,减20,将结果写回文件

3. 线程B读取文件中的整数,加50,将结果写回文件

线程A和B同时工作,有可能发生以下情况:

1. 线程A读取了文件中的整数100,减20得到80

2. 同时线程B读取了文件中的整数100,加50得到150

3. 线程A将80写回文件

4. 线程B将150写回文件

这种情况下线程A的写入的结果被线程B覆盖了,产生了无效操作,可能产生与我们预期不符的结果。对于这种情况,需要保证“读取-处理-写入”过程不能被其他线程打断,可以使用MUTEX等方法改善。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/334852.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号