可以写&对于同一文件描述符,两个线程可以并行调用 fclose 吗?

发布于 2024-09-18 23:46:38 字数 71 浏览 2 评论 0原文

如果 fwrite & 会发生什么?对于同一个文件描述符,从两个线程并行调用 fclose ?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

挖鼻大婶 2024-09-25 23:46:38

POSIX 要求 FILE 访问是线程安全的,但是由于 fclose 关闭文件并使指针无效,所以没有办法(即这不仅仅是一个规范问题,而是一个基本问题)当另一个线程可能仍在访问 FILE 时,使用 fclose 是永远无法“修复”或消失的 API 问题。您需要自己进行锁定。

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.

樱娆 2024-09-25 23:46:38

fwritefcloseFILE 数据结构进行操作。由于这是一个较大的数据结构,它不仅仅存储文件描述符,所以答案是不好的。

除非您确保使用互斥体进行原子操作,否则不要这样做。

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.

像极了他 2024-09-25 23:46:38

对于这种情况,您需要定义方法的优先级。
您可以使用“同步”来控制方法。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文