multithreading 为什么我应该使用线程而不是使用进程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/617787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why should I use a thread vs. using a process?
提问by danmine
Separating different parts of a program into different processes seems (to me) to make a more elegant program than just threading everything. In what scenario would it make sense to make things run on a thread vs. separating the program into different processes? When should I use a thread?
将程序的不同部分分成不同的进程似乎(对我来说)使程序更优雅,而不仅仅是线程化所有内容。在什么情况下让事情在线程上运行与将程序分成不同的进程更有意义?我什么时候应该使用线程?
Edit
编辑
Anything on how (or if) they act differently with single-core and multi-core would also be helpful.
任何关于它们如何(或是否)在单核和多核上表现不同的事情也会有所帮助。
回答by Frederick The Fool
You'd prefer multiple threads over multiple processes for two reasons:
出于两个原因,您更喜欢多个线程而不是多个进程:
- Inter-thread communication (sharing data etc.) is significantly simpler to program than inter-process communication.
- Context switches between threads are faster than between processes. That is, it's quicker for the OS to stop one thread and start running another than do the same with two processes.
- 线程间通信(共享数据等)比进程间通信更易于编程。
- 线程之间的上下文切换比进程之间的切换要快。也就是说,操作系统停止一个线程并开始运行另一个线程比对两个进程执行相同操作更快。
Example:
例子:
Applications with GUIs typically use one thread for the GUI and others for background computation. The spellchecker in MS Office, for example, is a separate thread from the one running the Office user interface. In such applications, using multiple processes instead would result in slower performance and code that's tough to write and maintain.
具有 GUI 的应用程序通常将一个线程用于 GUI,其他线程用于后台计算。例如,MS Office 中的拼写检查器是一个独立于运行 Office 用户界面的线程。在此类应用程序中,改用多个进程会导致性能下降以及难以编写和维护的代码。
回答by simplyharsh
Well apart from advantages of using thread over process, like:
除了使用线程而不是进程的优点之外,例如:
Advantages:
好处:
- Much quicker to create a thread than a process.
- Much quicker to switch between threads than to switch between processes.
- Threads share data easily
- 创建线程比创建进程要快得多。
- 在线程之间切换比在进程之间切换要快得多。
- 线程轻松共享数据
Consider few disadvantages too:
还要考虑一些缺点:
- No security between threads.
- One thread can stomp on another thread's data.
- If one thread blocks, all threads in task block.
- 线程之间没有安全性。
- 一个线程可以踩踏另一个线程的数据。
- 如果一个线程阻塞,则任务中的所有线程都阻塞。
As to the important part of your question "When should I use a thread?"
至于你问题的重要部分“我什么时候应该使用线程?”
Well you should consider few facts that a threads should not alter the semantics of a program. They simply change the timing of operations. As a result, they are almost always used as an elegant solution to performance related problems. Here are some examples of situations where you might use threads:
好吧,您应该考虑线程不应改变程序语义的几个事实。他们只是改变了操作的时间。因此,它们几乎总是被用作性能相关问题的优雅解决方案。以下是您可能会使用线程的一些情况示例:
- Doing lengthy processing: When a windows application is calculating it cannot process any more messages. As a result, the display cannot be updated.
- Doing background processing: Some tasks may not be time critical, but need to execute continuously.
- Doing I/O work: I/O to disk or to network can have unpredictable delays. Threads allow you to ensure that I/O latency does not delay unrelated parts of your application.
- 进行冗长的处理:当 Windows 应用程序正在计算时,它无法处理更多消息。因此,无法更新显示。
- 做后台处理:有些任务可能对时间不敏感,但需要连续执行。
- 执行 I/O 工作:到磁盘或网络的 I/O 可能有不可预测的延迟。线程允许您确保 I/O 延迟不会延迟应用程序的不相关部分。
回答by flodin
You sure don't sound like a newbie. It's an excellent observation that processes are, in many ways, more elegant. Threads are basically an optimization to avoid too many transitions or too much communication between memory spaces.
你听起来肯定不像个新手。这是一个很好的观察结果,即流程在许多方面都更加优雅。线程基本上是一种优化,以避免内存空间之间的太多转换或太多通信。
Superficially using threads may also seem like it makes your program easier to read and write, because you can share variables and memory between the threads freely. In practice, doing that requires very careful attention to avoid race conditions or deadlocks.
从表面上看,使用线程似乎也使您的程序更易于读写,因为您可以在线程之间自由共享变量和内存。在实践中,这样做需要非常小心,以避免竞争条件或死锁。
There are operating-system kernels (most notably L4) that try very hard to improve the efficiency of inter-process communication. For such systems one could probably make a convincing argument that threads are pointless.
有操作系统内核(最著名的是L4)非常努力地提高进程间通信的效率。对于这样的系统,人们可能会提出一个令人信服的论点,即线程毫无意义。
回答by BenB
I assume you already know you need a thread or a process, so I'd say the main reason to pick one over the other would be data sharing.
我假设你已经知道你需要一个线程或一个进程,所以我认为选择一个的主要原因是数据共享。
Use of a process means you also need Inter Process Communication (IPC) to get data in and out of the process. This is a good thing if the process is to be isolated though.
使用进程意味着您还需要进程间通信 (IPC) 来获取进出进程的数据。不过,如果要隔离进程,这是一件好事。
回答by Sanjay
I agree to most of the answers above. But speaking from design perspective i would rather go for a thread when i want set of logically co-related operations to be carried out parallel. For example if you run a word processor there will be one thread running in foreground as an editor and other thread running in background auto saving the document at regular intervals so no one would design a process to do that auto saving task separately.
我同意上面的大部分答案。但是从设计的角度来看,当我想要并行执行一组逻辑上相关的操作时,我宁愿选择一个线程。例如,如果您运行文字处理器,将有一个线程作为编辑器在前台运行,而另一个线程在后台运行,会定期自动保存文档,因此没有人会设计一个进程来单独执行该自动保存任务。
回答by Tim
In addition to the other answers, maintaining and deploying a single process is a lot simpler than having a few executables.
除了其他答案之外,维护和部署单个进程比拥有几个可执行文件要简单得多。
One would use multiple processes/executables to provide a well-defined interface/decoupling so that one part or the other can be reused or reimplemented more easily than keeping all the functionality in one process.
人们会使用多个进程/可执行文件来提供定义良好的接口/解耦,以便比将所有功能保留在一个进程中更容易重用或重新实现其中一个部分。
回答by pcodex
I would like to answer this in a different way. "It depends on your application's working scenario and performance SLA" would be my answer.
我想换一种方式来回答这个问题。“这取决于您的应用程序的工作场景和性能 SLA”将是我的答案。
For instance threads may be sharing the same address space and communication between threads may be faster and easier but it is also possible that under certain conditions threads deadlock and then what do you think would happen to your process.
例如,线程可能共享相同的地址空间,线程之间的通信可能更快更容易,但也有可能在某些条件下线程死锁,然后您认为您的进程会发生什么。
Even if you are a programming whiz and have used all the fancy thread synchronization mechanisms to prevent deadlocks it certainly is not rocket science to see that unless a deterministic model is followed which may be the case with hard real time systems running on Real Time OSes where you have a certain degree of control over thread priorities and can expect the OS to respect these priorities it may not be the case with General Purpose OSes like Windows.
即使你是一个编程高手并且已经使用了所有花哨的线程同步机制来防止死锁,但除非遵循确定性模型,否则在实时操作系统上运行的硬实时系统可能就是这种情况,这肯定不是火箭科学您对线程优先级有一定程度的控制,并且可以期望操作系统尊重这些优先级,但对于像 Windows 这样的通用操作系统可能不是这种情况。
From a Design perspective too you might want to isolate your functionality into independent self contained modules where they may not really need to share the same address space or memory or even talk to each other. This is a case where processes will make sense.
从设计的角度来看,您也可能希望将您的功能隔离到独立的自包含模块中,在这些模块中它们可能不需要共享相同的地址空间或内存,甚至不需要相互通信。在这种情况下,流程是有意义的。
Take the case of Google Chrome where multiple processes are spawned as opposed to most browsers which use a multi-threaded model. Each tab in Chrome can be talking to a different server and rendering a different website. Imagine what would happen if one website stopped responding and if you had a thread stalled due to this, the entire browser would either slow down or come to a stop. So Google decided to spawn multiple processes and that is why even if one tab freezes you can still continue using other tabs of your Chrome browser.
以 Google Chrome 为例,其中产生多个进程,而不是大多数使用多线程模型的浏览器。Chrome 中的每个选项卡都可以与不同的服务器通信并呈现不同的网站。想象一下,如果一个网站停止响应会发生什么,如果您的线程因此而停滞,整个浏览器要么变慢,要么停止。因此 Google 决定生成多个进程,这就是为什么即使一个选项卡冻结,您仍然可以继续使用 Chrome 浏览器的其他选项卡。
回答by Suresh
Came across this post. Interesting discussion. but I felt one point is missing or indirectly pointed.
偶然看到这个帖子。有趣的讨论。但我觉得缺少一点或间接指出了一点。
Creating a new process is costly because of all of the data structures that must be allocated and initialized. The process is subdivided into different threads of control to achieve multithreading inside the process.
由于必须分配和初始化所有数据结构,因此创建新进程的成本很高。将进程细分为不同的控制线程,实现进程内部的多线程。
Using a thread or a process to achieve the target is based on your program usage requirements and resource utilization.
使用线程或进程来实现目标是根据您的程序使用要求和资源利用率。