- 论坛徽章:
- 17
|
我从posix的角度来解释一下这个问题:
首先我们根据posix的规定可以明定哪些系统调用是线程安全的"A function that may be safely invoked concurrently by multiple threads. Each function defined in the System Interfaces volume of POSIX.1-2008 is thread-safe unless explicitly stated otherwise. ",由标准的定义可知除非另行说明,否则常见的系统调用都是线程安全的。那么具体到write,其规定中并没有直接说明线程安全的问题,但着重说明了多个write可能导致的数据覆盖问题。write具体做了什么由如下规定"On a regular file or other file capable of seeking, the actual writing of data shall proceed from the position in the file indicated by the file offset associated with fildes. Before successful return from write(), the file offset shall be incremented by the number of bytes actually written. On a regular file, if the position of the last byte written is greater than or equal to the length of the file, the length of the file shall be set to this position plus one. ",从上面的操作可知write不是个原子操作,一次成功的write需要seeking和writing两个动作,所以原则上来讲write是非线程安全的。进而关于write有如下规定"This volume of POSIX.1-2008 does not specify behavior of concurrent writes to a file from multiple processes. Applications should use some form of concurrency control.",显然多进程操作同一文件肯定是需要同步的,但是多线程就没有更多的规定了,只能推断write是非线程安全的(因为不是原子操作),至于write写socket那么就肯定是线程安全的,因为有如下规定"If fildes refers to a socket, write ( ) shall be equivalent to send ( ) with no flags set.",而且send是线程安全的。 |
|