本文共 3018 字,大约阅读时间需要 10 分钟。
It appears that school, tutorials, or whatever is teaching about threads a whole lot these days, and most designs I see from people learning the ropes involves a number of threads. However, threads cause bugs, and cause extra synchronization cost that's not easily visible, and not easily redeemable. I worked on the BeOS, where we used threads out the wazoo. We made threads very, very cheap, but in the end, we were still actually too heavy on threads in our designs -- live and learn. A typical threaded server design proposal looks something like:
| |
| |
This approach accomplishes the same thing, but it does it without the subtle race conditions and synchronization penalties that come from a threaded design. There is a danger that scheduled tasks will be started after their scheduled time. The total time they could be delayed by is the sum of time it takes to read things from input, process them, and send to the output. However, this is a bounded amount of time, and on a single-CPU system, this bound is lower than the maximum latency you'd get with a four-thread program on a dual-CPU system in the worst case. If you need near-real-time scheduled tasks, then a general-purpose OS may not be your best choice. If you still need this, then perhaps those special tasks should actually go in their own thread, because that might be one of the special cases... When should you use threads?I've seen threads really work well in the following cases:
[Summary] 优点 1. 在多处理器上的多个thread并行: 尤其是计算密集型任务 2. 多个thread的并发, 能改善响应速度和性能, 防止因为I/O等阻塞操作导致服务不可用, 同时可以把turning synchronous system APIs (gethostbyname(), file I/O etc) into asynchronous APIs, 而且asynchronous I/O 通常比thread更复杂。3. 更清晰的编程模型。、4. I/O 密集型任务采用多thread来等待不同的I/O操作,也能提高性能。
缺点: 1. Thread的同步,死锁, 时序依赖关系, race condition, thread之间的切换 所带来的额外开销。 2. 难以调试。 |
转载地址:http://ydzvb.baihongyu.com/