开发者

question about blocking i/o in a thread

开发者 https://www.devze.com 2023-02-02 05:54 出处:网络
I\'m using pthreads on Linux, and one of my threads periodically calls the write function on a device file descriptor.If the write call takes a while to finish, will my th开发者_JAVA技巧read be suspen

I'm using pthreads on Linux, and one of my threads periodically calls the write function on a device file descriptor. If the write call takes a while to finish, will my th开发者_JAVA技巧read be suspended so other threads can run? I didn't set any of the scheduling features of pthreads, so my question is about default thread behavior.


So long as nothing else is trying to write to the same resource, the other threads should run while the writing thread waits for its write to complete.


If a write() call blocks, only the calling thread is suspended. This is documented in the POSIX spec for write():

If there is enough space for all the data requested to be written immediately, the implementation should do so. Otherwise, the calling thread may block; that is, pause until enough space is available for writing.

Note that it says calling thread, not calling process.


See if blocking behavior is explicitly defined here http://www.akkadia.org/drepper/nptl-design.pdf


In principle, YES, other threads can run.

But be aware that some filesystems have locking mechnisms which permit only one concurrent IO operation on a single file. So if another thread does another IO on the same file (even if it's via a different file descriptor) it MAY block it for some of the duration of the write() system call.

There are also other in-kernel locks for other facililties. Most of them will not block other threads running unless they're doing closely related activities, however.


If your device file descriptor is a shared resource, you have to take care of locking. But once it's thread-safe, calls to such shared resource are serialized, thus if one thread writes, the rest are blocked. If locking is not implemented, the data may be garbled.

0

精彩评论

暂无评论...
验证码 换一张
取 消