什么时候使用进程和线程?

发布于 2024-10-14 21:34:59 字数 52 浏览 1 评论 0原文

我知道线程和进程之间理论上的区别。但在实际中何时使用线程和进程,因为两者都会做相同的工作。

I know the theoretical difference between the thread and process. But in practical when to use the thread and process because both will does the same work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

埋情葬爱 2024-10-21 21:34:59

一般来说(并且因操作系统而异):

  • 线程通常比进程轻量级
  • 进程在操作之间提供更好的隔离
  • 线程在进程内提供更简单的数据共享和协调

通常,中间点对我来说是最重要的 - 如果你真的、真的不希望两个操作相互干扰,只要一个进程崩溃不会影响另一个操作,请使用单独的进程。否则我个人会去寻找线程。

(我假设这两种模型都可用 - 如果您想运行单独的可执行文件,那么在现有线程中很难做到这一点,至少在我知道的大多数环境中是这样。)

In general (and it varies by operating system):

  • Threads are usually lighter-weight than processes
  • Processes provide better isolation between actions
  • Threads provide simpler data sharing and coordination within the process

Typically the middle point is the kicker for me - if you really, really don't want two actions to interfere with each other, to the extent that one process going belly-up doesn't affect the other action, use separate processes. Otherwise I personally go for threads.

(I'm assuming that both models are available - if you want to run a separate executable, that's going to be pretty hard to do within an existing thread, at least in most environments I'm aware of.)

懒的傷心 2024-10-21 21:34:59

线程是进程的小计。因此,主要区别在于内存分配和 CPU 时间调度:

  • 操作系统处理每个进程的内存并为进程安排执行时间,为线程
  • 分配内存(在每个进程允许的范围内)并为线程安排执行时间(在每个进程的给定执行时间范围内)

除此之外,还有很多细微的定义差异,例如硬件分配(线程可以共享由其进程锁定的硬件)、通信(取决于平台/语言/运行时,线程可以共享变量,进程需要管道来共享信息)等如果您将线程视为原子实体,则这种区别还有更多内容,而在这种情况下,进程将是对这些实体进行分组的方式。

Thread is a subtotal of a process. Hereby the main difference is memory allocation and CPU time scheduling:

  • operating system handles memory per process and schedules execution time for processes
  • you allocate memory (within the bounds allowed per process) and you schedule execution time (within given execution timeframe per process) for threads

Other than that there's a lot of minor defining differences, like hardware allocation (threads can share hardware locked by their process), communication (depending on the platform/language/runtime, threads can share variables, processes need a pipe to share information) etc. There's much more in this distinction if you think of a thread as of an atomic entity, whilst process in that case would be the way to group these entities.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文