Can fwrite & fclose be called parallely from two t

2019-05-04 20:02发布

What will happen if fwrite & fclose are called in parallel from two threads for the same file descriptor?

3条回答
贼婆χ
2楼-- · 2019-05-04 20:30

POSIX requires FILE access to be thread-safe, but since fclose closes the file and invalidates the pointer, there is no way (i.e. it's not just a specification issue but a fundamental API issue that could never be "fixed" or made to go away) to use fclose when another thread might be accessing the FILE still. You'll need to do your own locking.

查看更多
我想做一个坏孩纸
3楼-- · 2019-05-04 20:49

For such a circumstance you need to define priorities of your methods. You can control the methods with "synchronized".

查看更多
不美不萌又怎样
4楼-- · 2019-05-04 20:55

fwrite and fclose operate on the FILE data structure. Since this is a largish data structure that does store more than just the file descriptor, the answer is bad things.

Don't do this unless you ensure atomic operation using mutexes.

查看更多
登录 后发表回答