C了解和线程安全(Linux版) [英] C read and thread safety (linux)

查看:332
本文介绍了C了解和线程安全(Linux版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你调用会发生什么(或,或两者)在两个不同的线程,在同样的文件描述符(可以说,我们有兴趣了解的本地文件,并且它是一个套接字文件描述符),无需使用显式同步机制?

What would happen if you call read (or write, or both) in two different thread, on the same file descriptor (lets says we are interested about a local file, and a it's a socket file descriptor), without using explicitly a synchronization mechanism?

读取和写入系统调用都是,所以,单核CPU,它可能不走运,两个读会被执行在同一时间。但随着多内核...

Read and Write are syscall, so, on a single core CPU, it's probably unlucky that two read would be executed "at the same time". But with multiple cores...

什么Linux内核会做什么?

What the linux kernel will do?

和让我们可以更广泛一点:是的行为总是对其他内核相同(如BSD系统)

And let's be a bit more general : is the behavior always the same for other kernels (like BSDs) ?

编辑:根据密切文档,我们应该确保文件描述符不使用在其他线程系统调用。因此,接缝的显式同步将关闭文件描述符之前,需要(等等,还绕读/写,如果线程可以称之为仍在运行)。

Edit : According to the close documentation, we should be sure that the file descriptor isn't used by a syscall in an other thread. So it seams that explicit synchronization would be required before closing a file descriptor (and so, also around read/write if thread that may call it are still running).

推荐答案

任何系统级(系统调用)文件描述符的访问是线程安全的在所有主流的类UNIX操作系统。
虽然根据患者的年龄它们不必信号安全

Any system level (syscall) file descriptor access is thread safe in all mainstream UNIX-like OSes. Though depending on the age they are not necessarily signal safe.

如果你调用接受或者从两个不同的任务文件描述符类似然后内核的内部锁定机制将解决冲突。

If you call read, write, accept or similar on a file descriptor from two different tasks then the kernel's internal locking mechanism will resolve contention.

有关读取每个字节可能是只读一次,虽然和写入将在任何未定义的顺序去了。

For reads each byte may be only read once though and writes will go in any undefined order.

标准输入输出库函数 FREAD FWRITE 和合作。也有通过在控制结构默认内部锁定,尽管通过使用标志,可以禁用

The stdio library functions fread, fwrite and co. also have by default internal locking on the control structures, though by using flags it is possible to disable that.

这篇关于C了解和线程安全(Linux版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆