为什么线程可以被认为是

为什么线程可以被认为是

本文介绍了为什么线程可以被认为是“邪恶的"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 SQLite常见问题解答 ,并出现在这段话中:

I was reading the SQLite FAQ, and came upon this passage:

我不太理解线程是邪恶的"这一说法.如果是这样,那有什么选择呢?

I don't quite understand the statement "Thread are evil". If that is true, then what is the alternative?

我对线程的肤浅理解是:

My superficial understanding of threads is:

  • 线程使并发发生.否则,CPU的能力将被浪费,等待(例如)缓慢的I/O.
  • 但是不好的是,您必须同步逻辑以避免争用,并且必须保护共享资源.

注意:由于我不熟悉Windows上的线程,因此希望讨论仅限于Linux/Unix线程.

Note: As I am not familiar with threads on Windows, I hope the discussion will be limited to Linux/Unix threads.

推荐答案

当人们说线程是邪恶的"时,通常在说过程是好的"的情况下这样做.线程隐式共享所有应用程序状态和句柄(并且线程本地选项是选择加入的).这意味着在访问共享数据时,有很多机会忘记同步(甚至不了解您需要同步!).

When people say that "threads are evil", the usually do so in the context of saying "processes are good". Threads implicitly share all application state and handles (and thread locals are opt-in). This means that there are plenty of opportunities to forget to synchronize (or not even understand that you need to synchronize!) while accessing that shared data.

进程具有单独的内存空间,并且它们之间的任何通信都是显式的.此外,用于进程间通信的原语通常是这样的,您根本不需要进行同步(例如管道).而且,您仍然可以根据需要使用共享内存直接共享状态,但这在每个给定实例中也是明确的.因此,犯错的机会更少,并且代码的意图更加明确.

Processes have separate memory space, and any communication between them is explicit. Furthermore, primitives used for interprocess communication are often such that you don't need to synchronize at all (e.g. pipes). And you can still share state directly if you need to, using shared memory, but that is also explicit in every given instance. So there are fewer opportunities to make mistakes, and the intent of the code is more explicit.

这篇关于为什么线程可以被认为是“邪恶的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:37