何时多线程不是一个好主意?

时间:2022-06-29 20:59:52

I was recently working on an application that sent and received messages over Ethernet and Serial. I was then tasked to add the monitoring of DIO discretes. I throught,

我最近正致力于通过以太网和串口发送和接收消息的应用程序。然后,我负责添加对DIO离散度的监控。我通过,

"No reason to interrupt the main thread which is involved in message processing, I'll just create another thread that monitors DIO."

“没有理由中断消息处理中涉及的主线程,我只是创建另一个监视DIO的线程。”

This decision, however, proved to be poor. Sometimes the main thread would be interrupted between a Send and a Receive serial message. This interruption would disrupt the timing and alas, messages would be lost (forever).

然而,这一决定证明是不好的。有时,主线程将在发送和接收串行消息之间中断。这种中断会扰乱时间,唉,消息会永远丢失。

I found another way to monitor the DIO without using another thread and Ethernet and Serial communication were restored to their correct functionality.

我找到了另一种监控DIO而不使用其他线程的方法,并且以太网和串行通信恢复了正常的功能。

The whole fiasco, however, got me thinking. Are their any general guidelines about when not to use multiple-threads and/or does anyone have anymore examples of situations when using multiple-threads is not a good idea?

然而,整个惨败让我思考。他们关于何时不使用多线程的任何一般指导和/或任何人在使用多线程时是否有任何情况的例子都不是一个好主意?

**EDIT:Based on your comments and after scowering the internet for information, I have composed a blog post entitled When is multi-threading not a good idea?

**编辑:根据您的意见,在搜索互联网获取信息后,我撰写了一篇博文,题为“多线程什么时候不是一个好主意?

14 个解决方案

#1


15  

  1. On a single processor machine and a desktop application, you use multi threads so you don't freeze the app but for nothing else really.
  2. 在单处理器计算机和桌面应用程序上,您使用多线程,因此您不会冻结应用程序,但实际上没有其他任何内容。

  3. On a single processor server and a web based app, no need for multi threading because the web server handles most of it.
  4. 在单处理器服务器和基于Web的应用程序上,不需要多线程,因为Web服务器处理大部分内容。

  5. On a multi-processor machine and desktop app, you are suggested to use multi threads and parallel programming. Make as many threads as there are processors.
  6. 在多处理器计算机和桌面应用程序上,建议您使用多线程和并行编程。制作与处理器一样多的线程。

  7. On a multi-processor server and a web based app, no need again for multi threads because the web server handles it.
  8. 在多处理器服务器和基于Web的应用程序上,不再需要多线程,因为Web服务器会处理它。

In total, if you use multiple threads for other than un-freezing desktop apps and any other generic answer, you will make the app slower if you have a single core machine due to the threads interrupting each other.

总的来说,如果您使用多个线程而不是冻结桌面应用程序和任何其他通用答案,如果由于线程相互中断而导致单个核心计算机,则会使应用程序变慢。

Why? Because of the hardware switches. It takes time for the hardware to switch between threads in total. On a multi-core box, go ahead and use 1 thread for each core and you will greatly see a ramp up.

为什么?因为硬件开关。硬件总是在线程之间切换需要时间。在一个多核盒子上,继续使用每个核心1个线程,你会看到一个提升。

#2


6  

To paraphrase an old quote: A programmer had a problem. He thought, "I know, I'll use threads." Now the programmer has two problems. (Often attributed to JWZ, but it seems to predate his use of it talking about regexes.)

用一句旧话来解释:程序员遇到了问题。他想,“我知道,我会使用线程。”现在程序员有两个问题。 (通常归因于JWZ,但似乎早于他使用它来谈论正则表达式。)

A good rule of thumb is "Don't use threads, unless there's a very compelling reason to use threads." Multiple threads are asking for trouble. Try to find a good way to solve the problem without using multiple threads, and only fall back to using threads if avoiding it is as much trouble as the extra effort to use threads. Also, consider switching to multiple threads if you're running on a multi-core/multi-CPU machine, and performance testing of the single threaded version shows that you need the performance of the extra cores.

一个好的经验法则是“不要使用线程,除非有一个非常令人信服的理由使用线程。”多线程都在寻找麻烦。尝试在不使用多个线程的情况下找到解决问题的好方法,并且只有在避免使用线程时才会回退使用线程,这与使用线程的额外工作一样麻烦。此外,如果您在多核/多CPU计算机上运行,​​请考虑切换到多个线程,单线程版本的性能测试表明您需要额外核心的性能。

#3


6  

Multi-threading is a bad idea if:

如果出现以下情况,多线程是一个坏主意:

  • Several threads access and update the same resource (set a variable, write to a file), and you don't understand thread safety.

    几个线程访问并更新相同的资源(设置变量,写入文件),并且您不了解线程安全性。

  • Several threads interact with each other and you don't understand mutexes and similar thread-management tools.

    几个线程相互交互,您不了解互斥锁和类似的线程管理工具。

  • Your program uses static variables (threads typically share them by default).

    您的程序使用静态变量(线程通常默认共享它们)。

  • You haven't debugged concurrency issues.

    您尚未调试并发问题。

#4


4  

Actually, multi threading is not scalable and is hard to debug, so it should not be used in any case if you can avoid it. There is few cases where it is mandatory : when performance on a multi CPU matters, or when you deal whith a server that have a lot of clients taking a long time to answer.

实际上,多线程不可扩展且难以调试,因此如果可以避免,则不应该在任何情况下使用它。几乎没有必要的情况:当多CPU上的性能很重要时,或者当你处理有很多客户需要很长时间才能回答的服务器时。

In any other cases, you can use alternatives such as queue + cron jobs or else.

在任何其他情况下,您可以使用队列+ cron作业等替代方案。

#5


3  

You might want to take a look at the Dan Kegel's "The C10K problem" web page about handling multiple data sources/sinks.

您可能想看看Dan Kegel关于处理多个数据源/接收器的“C10K问题”网页。

Basically it is best to use minimal threads, which in sockets can be done in most OS's w/ some event system (or asynchronously in Windows using IOCP).

基本上最好使用最小线程,在套接字中可以在大多数操作系统中使用某些事件系统(或使用IOCP在Windows中异步)。

When you run into the case where the OS and/or libraries do not offer a way to perform communication in a non-blocking manner, it is best to use a thread-pool to handle them while reporting back to the same event loop.

当您遇到操作系统和/或库不提供以非阻塞方式执行通信的方式时,最好使用线程池来处理它们,同时向同一事件循环报告。

Example diagram of layout:

布局示例图:

Per CPU [*] EVENTLOOP   ------ Handles nonblocking I/O using OS/library utilities
                       |                        \___  Threadpool for various blocking events
                       Threadpool for handling the I/O messages that would take long

#6


2  

Multi-threading is not a good idea if you need to guarantee precise physical timing (like in your example). Other cons include intensive data exchange between threads. I would say multi-threading is good for really parallel tasks if you don't care much about their relative speed/priority/timing.

如果您需要保证精确的物理时序(如您的示例中),则多线程不是一个好主意。其他缺点包括线程之间的密集数据交换。我想如果你不太关心它们的相对速度/优先级/时间,那么多线程对于真正的并行任务是有益的。

#7


2  

A recent application I wrote that had to use multithreading (although not unbounded number of threads) was one where I had to communicate in several directions over two protocols, plus monitoring a third resource for changes. Both protocol libraries required a thread to run the respective event loop in, and when those were accounted for, it was easy to create a third loop for the resource monitoring. In addition to the event loop requirements, the messages going through the wires had strict timing requirements, and one loop couldn't be risked blocking the other, something that was further alleviated by using a multicore CPU (SPARC).

我写的一个最近的应用程序必须使用多线程(虽然不是无限数量的线程),我必须通过两个协议在多个方向上进行通信,并监视第三个资源的变化。两个协议库都需要一个线程来运行相应的事件循环,当考虑到这些时,很容易为资源监视创建第三个循环。除了事件循环要求之外,通过线路的消息具有严格的时序要求,并且一个环路不会有风险阻塞另一个环路,这通过使用多核CPU(SPARC)得到进一步缓解。

There were further discussions on whether each message processing should be considered a job that was given to a thread from a thread pool, but in the end that was an extension that wasn't worth the work.

进一步讨论了每个消息处理是否应该被视为从线程池给予线程的作业,但最终这是一个不值得工作的扩展。

All-in-all, threads should if possible only be considered when you can partition the work into well defined jobs (or series of jobs) such that the semantics are relatively easy to document and implement, and you can put an upper bound on the number of threads you use and that need to interact. Systems where this is best applied are almost message passing systems.

总而言之,只有当你可以将工作划分为明确定义的作业(或一系列作业)时才应考虑线程,这样语义相对容易记录和实现,并且你可以设置上限。您使用和需要交互的线程数。最适用的系统几乎是消息传递系统。

#8


2  

Multithreading is bad except in the single case where it is good. This case is

多线程很糟糕,除非它是好的单一情况。这个案子是

  1. The work is CPU Bound, or parts of it is CPU Bound
  2. 工作是CPU绑定,或部分是CPU绑定

  3. The work is parallelisable.
  4. 这项工作是可以并行的。

If either or both of these conditions are missing, multithreading is not going to be a winning strategy.

如果缺少这些条件中的任何一个或两个,多线程不会成为一个成功的策略。

If the work is not CPU bound, then you are waiting not on threads to finish work, but rather for some external event, such as network activity, for the process to complete its work. Using threads, there is the additional cost of context switches between threads, The cost of synchronization (mutexes, etc), and the irregularity of thread preemption. The alternative in most common use is asynchronous IO, in which a single thread listens to several io ports, and acts on whichever happens to be ready now, one at a time. If by some chance these slow channels all happen to become ready at the same time, It might seem like you will experience a slow-down, but in practice this is rarely true. The cost of handling each port individually is often comparable or better than the cost of synchronizing state on multiple threads as each channel is emptied.

如果工作不受CPU限制,那么您不是等待线程完成工作,而是等待一些外部事件(例如网络活动),以便流程完成其工作。使用线程,线程之间的上下文切换的额外成本,同步的成本(互斥等)以及线程抢占的不规则性。最常见的替代方案是异步IO,其中单个线程侦听多个io端口,并且对现在准备好的任何一个进行操作,一次一个。如果有可能这些慢速通道都在同一时间准备就绪,看起来你可能会遇到减速,但实际上这很少是真的。单独处理每个端口的成本通常与每个通道清空时在多个线程上同步状态的成本相当或更好。

Many tasks may be compute bound, but still not practical to use a multithreaded approach because the process must synchronise on the entire state. Such a program cannot benefit from multithreading because no work can be performed concurrently. Fortunately, most programs that require enormous amounts of CPU can be parallelized to some level.

许多任务可能是计算绑定的,但使用多线程方法仍然不实际,因为进程必须在整个状态上同步。这样的程序不能从多线程中受益,因为不能同时执行任何工作。幸运的是,大多数需要大量CPU的程序可以并行化到某种程度。

#9


1  

In priciple everytime there is no overhead for the caller to wait in a queue.

每次在原理中,调用者没有开销在队列中等待的开销。

#10


1  

A couple more possible reasons to use threads:

使用线程的几个可能的原因:

  1. Your platform lacks asynchronous I/O operations, e.g. Windows ME (No completion ports or overlapped I/O, a pain when porting XP applications that use them.) Java 1.3 and earlier.
  2. 您的平台缺少异步I / O操作,例如Windows ME(没有完成端口或重叠的I / O,移植使用它们的XP应用程序时很痛苦。)Java 1.3及更早版本。

  3. A third-party library function that can hang, e.g. if a remote server is down, and the library provides no way to cancel the operation and you can't modify it.
  4. 可以挂起的第三方库函数,例如如果远程服务器已关闭,并且库无法取消该操作,则无法对其进行修改。

Keeping a GUI responsive during intensive processing doesn't always require additional threads. A single callback function is usually sufficient.

在密集处理期间保持GUI响应并不总是需要额外的线程。单个回调函数通常就足够了。

If none of the above apply and I still want parallelism for some reason, I prefer to launch an independent process if possible.

如果以上都不适用,我仍然希望出于某种原因并行,我希望尽可能启动一个独立的过程。

#11


1  

I would say multi-threading is generally used to:

我想说多线程通常用于:

  1. Allow data processing in the background while a GUI remains responsive
  2. 当GUI保持响应时,允许在后台进行数据处理

  3. Split very big data analysis onto multiple processing units so that you can get your results quicker.
  4. 将非常大的数据分析拆分到多个处理单元,以便您可以更快地获得结果。

  5. When you're receiving data from some hardware and need something to continuously add it to a buffer while some other element decides what to do with it (write to disk, display on a GUI etc.).
  6. 当您从某些硬件接收数据并需要继续将其添加到缓冲区时,而其他一些元素决定如何处理它(写入磁盘,在GUI上显示等)。

So if you're not solving one of those issues, it's unlikely that adding threads will make your life easier. In fact it'll almost certainly make it harder because as others have mentioned; debugging mutithreaded applications is considerably more work than a single threaded solution.

因此,如果您没有解决其中一个问题,那么添加线程不太可能让您的生活更轻松。事实上,它几乎肯定会变得更难,因为正如其他人所说的那样;调试mutithreaded应用程序比单线程解决方案要多得多。

Security might be a reason to avoid using multiple threads (over multiple processes). See Google chrome for an example of multi-process safety features.

安全性可能是避免使用多个线程(多个进程)的原因。有关多进程安全功能的示例,请参阅Google Chrome。

#12


1  

Multi-threading is scalable, and will allow your UI to maintain its responsivness while doing very complicated things in the background. I don't understand where other responses are acquiring their information on multi-threading.

多线程是可扩展的,并且允许您的UI在后台执行非常复杂的操作时保持其响应性。我不明白其他回复在哪里获取有关多线程的信息。

When you shouldn't multi-thread is a mis-leading question to your problem. Your problem is this: Why did multi-threading my application cause serial / ethernet communications to fail?

当你不应该多线程是一个错误的问题你的问题。您的问题是这样的:为什么我的应用程序多线程导致串行/以太网通信失败?

The answer to that question will depend on the implementation, which should be discussed in another question. I know for a fact that you can have both ethernet and serial communications happening in a multi-threaded application at the same time as numerous other tasks without causing any data loss.

该问题的答案将取决于实施,应在另一个问题中讨论。我知道您可以在多线程应用程序中同时执行以太网和串行通信,同时执行许多其他任务,而不会导致任何数据丢失。

The one reason to not use multi-threading is:

不使用多线程的一个原因是:

  1. There is one task, and no user interface with which the task will interfere.
  2. 有一个任务,没有任务干扰的用户界面。

The reasons to use mutli-threading are:

使用多线程的原因是:

  1. Provides superior responsiveness to the user
  2. 为用户提供卓越的响应能力

  3. Performs multiple tasks at the same time to decrease overall execution time
  4. 同时执行多个任务以减少总体执行时间

  5. Uses more of the current multi-core CPUs, and multi-multi-cores of the future.
  6. 使用更多当前的多核CPU和未来的多核。

There are three basic methods of multi-threaded programming that make thread safety implemented with ease - you only need to use one for success:

有三种基本的多线程编程方法可以轻松实现线程安全 - 您只需使用一个即可获得成功:

  1. Thread Safe Data types passed between threads.
  2. 线程之间传递的线程安全数据类型。

  3. Thread Safe Methods in the threaded object to modify data passed between.
  4. 线程安全方法在线程对象中修改之间传递的数据。

  5. PostMessage capabilities to communicate between threads.
  6. PostMessage功能可以在线程之间进行通信。

#13


0  

Are the processes parallel? Is performance a real concern? Are there multiple 'threads' of execution like on a web server? I don't think there is a finite answer.

流程是否平行?表演真的是一个问题吗?在Web服务器上是否存在多个“执行线程”?我认为没有一个有限的答案。

#14


0  

A common source of threading issues is the usual approaches employed to synchronize data. Having threads share state and then implement locking at all the appropriate places is a major source of complexity for both design and debugging. Getting the locking right to balance stability, performance, and scalability is always a hard problem to solve. Even the most experienced experts get it wrong frequently. Alternative techniques to deal with threading can alleviate much of this complexity. The Clojure programming language implements several interesting techniques for dealing with concurrency.

线程问题的常见来源是用于同步数据的常用方法。让线程共享状态然后在所有适当的位置实现锁定是设计和调试的主要复杂因素。获得正确的锁定以平衡稳定性,性能和可扩展性始终是一个难以解决的问题。即使是经验最丰富的专家也经常弄错。处理线程的替代技术可以减轻这种复杂性。 Clojure编程语言实现了几种处理并发的有趣技术。

#1


15  

  1. On a single processor machine and a desktop application, you use multi threads so you don't freeze the app but for nothing else really.
  2. 在单处理器计算机和桌面应用程序上,您使用多线程,因此您不会冻结应用程序,但实际上没有其他任何内容。

  3. On a single processor server and a web based app, no need for multi threading because the web server handles most of it.
  4. 在单处理器服务器和基于Web的应用程序上,不需要多线程,因为Web服务器处理大部分内容。

  5. On a multi-processor machine and desktop app, you are suggested to use multi threads and parallel programming. Make as many threads as there are processors.
  6. 在多处理器计算机和桌面应用程序上,建议您使用多线程和并行编程。制作与处理器一样多的线程。

  7. On a multi-processor server and a web based app, no need again for multi threads because the web server handles it.
  8. 在多处理器服务器和基于Web的应用程序上,不再需要多线程,因为Web服务器会处理它。

In total, if you use multiple threads for other than un-freezing desktop apps and any other generic answer, you will make the app slower if you have a single core machine due to the threads interrupting each other.

总的来说,如果您使用多个线程而不是冻结桌面应用程序和任何其他通用答案,如果由于线程相互中断而导致单个核心计算机,则会使应用程序变慢。

Why? Because of the hardware switches. It takes time for the hardware to switch between threads in total. On a multi-core box, go ahead and use 1 thread for each core and you will greatly see a ramp up.

为什么?因为硬件开关。硬件总是在线程之间切换需要时间。在一个多核盒子上,继续使用每个核心1个线程,你会看到一个提升。

#2


6  

To paraphrase an old quote: A programmer had a problem. He thought, "I know, I'll use threads." Now the programmer has two problems. (Often attributed to JWZ, but it seems to predate his use of it talking about regexes.)

用一句旧话来解释:程序员遇到了问题。他想,“我知道,我会使用线程。”现在程序员有两个问题。 (通常归因于JWZ,但似乎早于他使用它来谈论正则表达式。)

A good rule of thumb is "Don't use threads, unless there's a very compelling reason to use threads." Multiple threads are asking for trouble. Try to find a good way to solve the problem without using multiple threads, and only fall back to using threads if avoiding it is as much trouble as the extra effort to use threads. Also, consider switching to multiple threads if you're running on a multi-core/multi-CPU machine, and performance testing of the single threaded version shows that you need the performance of the extra cores.

一个好的经验法则是“不要使用线程,除非有一个非常令人信服的理由使用线程。”多线程都在寻找麻烦。尝试在不使用多个线程的情况下找到解决问题的好方法,并且只有在避免使用线程时才会回退使用线程,这与使用线程的额外工作一样麻烦。此外,如果您在多核/多CPU计算机上运行,​​请考虑切换到多个线程,单线程版本的性能测试表明您需要额外核心的性能。

#3


6  

Multi-threading is a bad idea if:

如果出现以下情况,多线程是一个坏主意:

  • Several threads access and update the same resource (set a variable, write to a file), and you don't understand thread safety.

    几个线程访问并更新相同的资源(设置变量,写入文件),并且您不了解线程安全性。

  • Several threads interact with each other and you don't understand mutexes and similar thread-management tools.

    几个线程相互交互,您不了解互斥锁和类似的线程管理工具。

  • Your program uses static variables (threads typically share them by default).

    您的程序使用静态变量(线程通常默认共享它们)。

  • You haven't debugged concurrency issues.

    您尚未调试并发问题。

#4


4  

Actually, multi threading is not scalable and is hard to debug, so it should not be used in any case if you can avoid it. There is few cases where it is mandatory : when performance on a multi CPU matters, or when you deal whith a server that have a lot of clients taking a long time to answer.

实际上,多线程不可扩展且难以调试,因此如果可以避免,则不应该在任何情况下使用它。几乎没有必要的情况:当多CPU上的性能很重要时,或者当你处理有很多客户需要很长时间才能回答的服务器时。

In any other cases, you can use alternatives such as queue + cron jobs or else.

在任何其他情况下,您可以使用队列+ cron作业等替代方案。

#5


3  

You might want to take a look at the Dan Kegel's "The C10K problem" web page about handling multiple data sources/sinks.

您可能想看看Dan Kegel关于处理多个数据源/接收器的“C10K问题”网页。

Basically it is best to use minimal threads, which in sockets can be done in most OS's w/ some event system (or asynchronously in Windows using IOCP).

基本上最好使用最小线程,在套接字中可以在大多数操作系统中使用某些事件系统(或使用IOCP在Windows中异步)。

When you run into the case where the OS and/or libraries do not offer a way to perform communication in a non-blocking manner, it is best to use a thread-pool to handle them while reporting back to the same event loop.

当您遇到操作系统和/或库不提供以非阻塞方式执行通信的方式时,最好使用线程池来处理它们,同时向同一事件循环报告。

Example diagram of layout:

布局示例图:

Per CPU [*] EVENTLOOP   ------ Handles nonblocking I/O using OS/library utilities
                       |                        \___  Threadpool for various blocking events
                       Threadpool for handling the I/O messages that would take long

#6


2  

Multi-threading is not a good idea if you need to guarantee precise physical timing (like in your example). Other cons include intensive data exchange between threads. I would say multi-threading is good for really parallel tasks if you don't care much about their relative speed/priority/timing.

如果您需要保证精确的物理时序(如您的示例中),则多线程不是一个好主意。其他缺点包括线程之间的密集数据交换。我想如果你不太关心它们的相对速度/优先级/时间,那么多线程对于真正的并行任务是有益的。

#7


2  

A recent application I wrote that had to use multithreading (although not unbounded number of threads) was one where I had to communicate in several directions over two protocols, plus monitoring a third resource for changes. Both protocol libraries required a thread to run the respective event loop in, and when those were accounted for, it was easy to create a third loop for the resource monitoring. In addition to the event loop requirements, the messages going through the wires had strict timing requirements, and one loop couldn't be risked blocking the other, something that was further alleviated by using a multicore CPU (SPARC).

我写的一个最近的应用程序必须使用多线程(虽然不是无限数量的线程),我必须通过两个协议在多个方向上进行通信,并监视第三个资源的变化。两个协议库都需要一个线程来运行相应的事件循环,当考虑到这些时,很容易为资源监视创建第三个循环。除了事件循环要求之外,通过线路的消息具有严格的时序要求,并且一个环路不会有风险阻塞另一个环路,这通过使用多核CPU(SPARC)得到进一步缓解。

There were further discussions on whether each message processing should be considered a job that was given to a thread from a thread pool, but in the end that was an extension that wasn't worth the work.

进一步讨论了每个消息处理是否应该被视为从线程池给予线程的作业,但最终这是一个不值得工作的扩展。

All-in-all, threads should if possible only be considered when you can partition the work into well defined jobs (or series of jobs) such that the semantics are relatively easy to document and implement, and you can put an upper bound on the number of threads you use and that need to interact. Systems where this is best applied are almost message passing systems.

总而言之,只有当你可以将工作划分为明确定义的作业(或一系列作业)时才应考虑线程,这样语义相对容易记录和实现,并且你可以设置上限。您使用和需要交互的线程数。最适用的系统几乎是消息传递系统。

#8


2  

Multithreading is bad except in the single case where it is good. This case is

多线程很糟糕,除非它是好的单一情况。这个案子是

  1. The work is CPU Bound, or parts of it is CPU Bound
  2. 工作是CPU绑定,或部分是CPU绑定

  3. The work is parallelisable.
  4. 这项工作是可以并行的。

If either or both of these conditions are missing, multithreading is not going to be a winning strategy.

如果缺少这些条件中的任何一个或两个,多线程不会成为一个成功的策略。

If the work is not CPU bound, then you are waiting not on threads to finish work, but rather for some external event, such as network activity, for the process to complete its work. Using threads, there is the additional cost of context switches between threads, The cost of synchronization (mutexes, etc), and the irregularity of thread preemption. The alternative in most common use is asynchronous IO, in which a single thread listens to several io ports, and acts on whichever happens to be ready now, one at a time. If by some chance these slow channels all happen to become ready at the same time, It might seem like you will experience a slow-down, but in practice this is rarely true. The cost of handling each port individually is often comparable or better than the cost of synchronizing state on multiple threads as each channel is emptied.

如果工作不受CPU限制,那么您不是等待线程完成工作,而是等待一些外部事件(例如网络活动),以便流程完成其工作。使用线程,线程之间的上下文切换的额外成本,同步的成本(互斥等)以及线程抢占的不规则性。最常见的替代方案是异步IO,其中单个线程侦听多个io端口,并且对现在准备好的任何一个进行操作,一次一个。如果有可能这些慢速通道都在同一时间准备就绪,看起来你可能会遇到减速,但实际上这很少是真的。单独处理每个端口的成本通常与每个通道清空时在多个线程上同步状态的成本相当或更好。

Many tasks may be compute bound, but still not practical to use a multithreaded approach because the process must synchronise on the entire state. Such a program cannot benefit from multithreading because no work can be performed concurrently. Fortunately, most programs that require enormous amounts of CPU can be parallelized to some level.

许多任务可能是计算绑定的,但使用多线程方法仍然不实际,因为进程必须在整个状态上同步。这样的程序不能从多线程中受益,因为不能同时执行任何工作。幸运的是,大多数需要大量CPU的程序可以并行化到某种程度。

#9


1  

In priciple everytime there is no overhead for the caller to wait in a queue.

每次在原理中,调用者没有开销在队列中等待的开销。

#10


1  

A couple more possible reasons to use threads:

使用线程的几个可能的原因:

  1. Your platform lacks asynchronous I/O operations, e.g. Windows ME (No completion ports or overlapped I/O, a pain when porting XP applications that use them.) Java 1.3 and earlier.
  2. 您的平台缺少异步I / O操作,例如Windows ME(没有完成端口或重叠的I / O,移植使用它们的XP应用程序时很痛苦。)Java 1.3及更早版本。

  3. A third-party library function that can hang, e.g. if a remote server is down, and the library provides no way to cancel the operation and you can't modify it.
  4. 可以挂起的第三方库函数,例如如果远程服务器已关闭,并且库无法取消该操作,则无法对其进行修改。

Keeping a GUI responsive during intensive processing doesn't always require additional threads. A single callback function is usually sufficient.

在密集处理期间保持GUI响应并不总是需要额外的线程。单个回调函数通常就足够了。

If none of the above apply and I still want parallelism for some reason, I prefer to launch an independent process if possible.

如果以上都不适用,我仍然希望出于某种原因并行,我希望尽可能启动一个独立的过程。

#11


1  

I would say multi-threading is generally used to:

我想说多线程通常用于:

  1. Allow data processing in the background while a GUI remains responsive
  2. 当GUI保持响应时,允许在后台进行数据处理

  3. Split very big data analysis onto multiple processing units so that you can get your results quicker.
  4. 将非常大的数据分析拆分到多个处理单元,以便您可以更快地获得结果。

  5. When you're receiving data from some hardware and need something to continuously add it to a buffer while some other element decides what to do with it (write to disk, display on a GUI etc.).
  6. 当您从某些硬件接收数据并需要继续将其添加到缓冲区时,而其他一些元素决定如何处理它(写入磁盘,在GUI上显示等)。

So if you're not solving one of those issues, it's unlikely that adding threads will make your life easier. In fact it'll almost certainly make it harder because as others have mentioned; debugging mutithreaded applications is considerably more work than a single threaded solution.

因此,如果您没有解决其中一个问题,那么添加线程不太可能让您的生活更轻松。事实上,它几乎肯定会变得更难,因为正如其他人所说的那样;调试mutithreaded应用程序比单线程解决方案要多得多。

Security might be a reason to avoid using multiple threads (over multiple processes). See Google chrome for an example of multi-process safety features.

安全性可能是避免使用多个线程(多个进程)的原因。有关多进程安全功能的示例,请参阅Google Chrome。

#12


1  

Multi-threading is scalable, and will allow your UI to maintain its responsivness while doing very complicated things in the background. I don't understand where other responses are acquiring their information on multi-threading.

多线程是可扩展的,并且允许您的UI在后台执行非常复杂的操作时保持其响应性。我不明白其他回复在哪里获取有关多线程的信息。

When you shouldn't multi-thread is a mis-leading question to your problem. Your problem is this: Why did multi-threading my application cause serial / ethernet communications to fail?

当你不应该多线程是一个错误的问题你的问题。您的问题是这样的:为什么我的应用程序多线程导致串行/以太网通信失败?

The answer to that question will depend on the implementation, which should be discussed in another question. I know for a fact that you can have both ethernet and serial communications happening in a multi-threaded application at the same time as numerous other tasks without causing any data loss.

该问题的答案将取决于实施,应在另一个问题中讨论。我知道您可以在多线程应用程序中同时执行以太网和串行通信,同时执行许多其他任务,而不会导致任何数据丢失。

The one reason to not use multi-threading is:

不使用多线程的一个原因是:

  1. There is one task, and no user interface with which the task will interfere.
  2. 有一个任务,没有任务干扰的用户界面。

The reasons to use mutli-threading are:

使用多线程的原因是:

  1. Provides superior responsiveness to the user
  2. 为用户提供卓越的响应能力

  3. Performs multiple tasks at the same time to decrease overall execution time
  4. 同时执行多个任务以减少总体执行时间

  5. Uses more of the current multi-core CPUs, and multi-multi-cores of the future.
  6. 使用更多当前的多核CPU和未来的多核。

There are three basic methods of multi-threaded programming that make thread safety implemented with ease - you only need to use one for success:

有三种基本的多线程编程方法可以轻松实现线程安全 - 您只需使用一个即可获得成功:

  1. Thread Safe Data types passed between threads.
  2. 线程之间传递的线程安全数据类型。

  3. Thread Safe Methods in the threaded object to modify data passed between.
  4. 线程安全方法在线程对象中修改之间传递的数据。

  5. PostMessage capabilities to communicate between threads.
  6. PostMessage功能可以在线程之间进行通信。

#13


0  

Are the processes parallel? Is performance a real concern? Are there multiple 'threads' of execution like on a web server? I don't think there is a finite answer.

流程是否平行?表演真的是一个问题吗?在Web服务器上是否存在多个“执行线程”?我认为没有一个有限的答案。

#14


0  

A common source of threading issues is the usual approaches employed to synchronize data. Having threads share state and then implement locking at all the appropriate places is a major source of complexity for both design and debugging. Getting the locking right to balance stability, performance, and scalability is always a hard problem to solve. Even the most experienced experts get it wrong frequently. Alternative techniques to deal with threading can alleviate much of this complexity. The Clojure programming language implements several interesting techniques for dealing with concurrency.

线程问题的常见来源是用于同步数据的常用方法。让线程共享状态然后在所有适当的位置实现锁定是设计和调试的主要复杂因素。获得正确的锁定以平衡稳定性,性能和可扩展性始终是一个难以解决的问题。即使是经验最丰富的专家也经常弄错。处理线程的替代技术可以减轻这种复杂性。 Clojure编程语言实现了几种处理并发的有趣技术。