为什么我应该使用线程而不是使用进程? [英] Why should I use a thread vs. using a process?

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

问题描述

将程序的不同部分分成不同的进程似乎(对我来说)比仅仅线程化所有的程序更优雅.在什么情况下让事情在线程上运行与将程序分成不同的进程更有意义?我什么时候应该使用线程?

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天全站免登陆