误解单线程和多线程编程之间的区别

误解单线程和多线程编程之间的区别

本文介绍了误解单线程和多线程编程之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对单线程编程和多线程编程之间的区别有误解,所以我想对以下问题做出一个答案,以使一切变得清晰.

I have a misunderstanding of the difference between single-threading and multi-threading programming, so I want an answer to the following question to make everything clear.

假设有9个独立的任务,而我想用一个单线程程序和一个多线程程序来完成它们.基本上是这样的:

Suppose that there are 9 independent tasks and I want to accomplish them with a single-threaded program and a multi-threaded program. Basically it will be something like this:

单线程:

- Execute task 1
- Execute task 2
- Execute task 3
- Execute task 4
- Execute task 5
- Execute task 6
- Execute task 7
- Execute task 8
- Execute task 9

多线程:

线程1:

- Execute task 1
- Execute task 2
- Execute task 3

线程2:

- Execute task 4
- Execute task 5
- Execute task 6

线程3:

- Execute task 7
- Execute task 8
- Execute task 9

据我了解,一次将仅执行一个一个线程(获取CPU),并且在完成量子操作后,线程调度程序会将CPU时间分配给另一个线程.

As I understand, only ONE thread will be executed at a time (get the CPU), and once the quantum is finished, the thread scheduler will give the CPU time to another thread.

那么,哪个程序会更早完成?它是多线程程序(逻辑上)吗?还是单线程程序(因为多线程有很多上下文切换需要一些时间)?为什么呢?请给我一个很好的解释:)

So, which program will be finished earlier? Is it the multi-threaded program (logically)? or is it the single-thread program (since the multi-threading has a lot of context-switching which takes some time)? and why? I need a good explanation please :)

推荐答案

这要视情况而定.

您有多少cpus?您的任务涉及多少I/O?

How many cpus do you have? How much I/O is involved in your tasks?

如果只有1个cpu,并且任务没有阻塞的I/O,则单线程将完成等于或快于多线程的速度,因为切换线程会产生开销.

If you have only 1 cpu, and the tasks have no blocking I/O, then the single threaded will finish equal to or faster than multi-threaded, as there is overhead to switching threads.

如果您有1个cpu,但是任务涉及大量的阻塞I/O,则假定使用I/O时可以完成工作,那么使用线程可能会加快速度.

If you have 1 cpu, but the tasks involve a lot of blocking I/O, you might see a speedup by using threading, assuming work can be done when I/O is in progress.

如果有多个CPU,则应该看到多线程实现比单线程实现了加速,因为可以并行执行多个线程.当然,除非任务由I/O主导,否则限制因素是设备速度,而不是CPU功耗.

If you have multiple cpus, then you should see a speedup with the multi-threaded implementation over the single threaded, since more than 1 thread can execute in parallel. Unless of course the tasks are I/O dominated, in which case the limiting factor is your device speed, not cpu power.

这篇关于误解单线程和多线程编程之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:13