为什么要使用线程还是使用进程? [英] Why should I use a thread vs. using a process?

查看:210
本文介绍了为什么要使用线程还是使用进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,将程序的不同部分分为不同的进程似乎比仅线程化所有程序更优雅.在什么情况下使事情在线程上运行而不是将程序分为不同的进程有意义?我什么时候应该使用线程?

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?

关于它们在单核和多核上如何(或是否)表现不同的任何事情也将有所帮助.

Anything on how (or if) they act differently with single-core and multi-core would also be helpful.

推荐答案

与多个进程相比,您更希望使用多个线程,原因有二:

You'd prefer multiple threads over multiple processes for two reasons:

  1. 线程间通信(共享数据等)比进程间通信要容易得多.
  2. 线程之间的上下文切换比进程之间的上下文切换要快.也就是说,操作系统停止一个线程并开始运行另一个线程的速度要快于两个进程.

示例:

具有GUI的应用程序通常将一个线程用于GUI,将其他线程用于后台计算.例如,MS Office中的拼写检查器是与运行Office用户界面的线程不同的线程.在这样的应用程序中,使用多个进程会导致性能降低以及难以编写和维护的代码.

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.

这篇关于为什么要使用线程还是使用进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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