什么是多线程程序,它如何工作? [英] What is a multithreading program and how does it work?

查看:512
本文介绍了什么是多线程程序,它如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是多线程程序,它如何工作?我读了一些文件,但我很困惑.我知道代码是逐行执行的,但是我不明白程序是如何管理的.
一个简单的答案将不胜感激.请使用c#示例(仅动画!)

What is a multithreading program and how does it work exactly? I read some documents but I'm confused. I know that code is executed line by line, but I can't understand how the program manages this.
A simple answer would be appreciated.c# example please (only animation!)

推荐答案

什么是多线程程序?它到底如何工作?

What is a multi-threading program and how does it work exactly?

有关此问题的有趣部分是有关该主题的完整书籍,但对于许多人来说仍然难以捉摸.我将尝试按下面详细的顺序进行说明.

Interesting part about this question is complete books are written on the topic, but still it is elusive to lot of people. I will try to explain in the order detailed underneath.

请注意,这仅是提供要点,这样的回答永远无法满足要求的深度和细节.关于视频,我遇到的最好的事情是付费订阅(Wintellect和Pluralsight)的一部分,假设您还没有订阅,请检查是否可以试听它们.

Please note this is just to provide a gist, an answer like this can never do justice to the depth and detail required. Regarding videos, best that I have come across are part of paid subscriptions (Wintellect and Pluralsight), check out if you can listen to them on trial basis, assuming you don't already have the subscription:

  1. Jeffery Ritcher的Wintellect (摘自他的书,通过C#进行CLR,线程基础知识的同一章)

  1. Wintellect by Jeffery Ritcher (from his Book, CLR via C#, has same chapter on Thread Fundamentals)

由Mike Woodring编写的CLR线程

说明顺序

  • 什么是线程?
  • 为什么引入线程是主要目的?
  • 使用Synchronization构造的陷阱以及如何避免这些陷阱?
  • 线程与线程池?
  • 多线程编程API的发展,例如并行API,任务API
  • 并发收集,用法?
  • 异步等待,线程但没有线程,为什么它们最适合IO

什么是线程?

What is a thread ?

这是软件实现,纯粹是Windows OS概念(multi-threaded architecture),它只是最低限度的工作单元. Windows OS上的每个进程至少都有一个线程,每个方法调用都在该线程上完成.每个进程可以具有多个线程,以并行执行多项操作(提供硬件支持). 其他基于Unix的OS是多进程体系结构,实际上在Windows中,即使是最复杂的软件(如Oracle.exe)也具有单个进程,并且具有多个线程用于不同的关键后台操作.

It is software implementation, which is purely a Windows OS concept (multi-threaded architecture), it is bare minimum unit of work. Every process on windows OS has at least one thread, every method call is done on the thread. Each process can have multiple threads, to do multiple things in parallel (provided hardware support). Other Unix based OS are multi process architecture, in fact in Windows, even the most complex piece of software like Oracle.exe have single process with multiple threads for different critical background operations.

为什么引入线程是主要目的?

Why were threads introduced, main purpose ?

与并发是主要目的的认识相反,鲁棒性导致引入线程,想象一下Windows上的每个进程都使用相同的线程(在最初的16位版本中)运行,并且其中一个进程崩溃,这仅意味着在大多数情况下系统重新启动即可恢复.并发操作的线程用法,因为可以在每个进程中调用多个线程,因此在下面进行了介绍.实际上,充分利用具有多个内核的处理器甚至是至关重要的.

Contrary to the perception that concurrency is the main purpose, it was robustness that lead to the introduction of threads, imagine every process on Windows is running using same thread (in the initial 16 bit version) and out of them one process crash, that simply means system restart to recover in most of the cases. Usage of threads for concurrent operations, as multiple of them can be invoked in each process, came in picture down the line. In fact it is even important to utilize the processor with multiple cores to its full ability.

陷阱以及如何避免使用同步结构?

Pitfalls and how to avoid using Synchronization constructs ?

更多的线程意味着,更多的工作可以同时完成,但是问题是,当访问相同的内存时,尤其是对于Write来说,那是因为它可能导致:

More threads means, more work completed concurrently, but issue comes, when same memory is accessed, especially for Write, as that's when it can lead to:

  1. 内存损坏
  2. 种族状况

另外,另一个问题是线程是非常昂贵的资源,每个线程都有一个线程环境块,即内核内存分配.同样,为了调度处理器核心上的每个线程,还花费时间进行上下文切换.滥用很可能导致巨大的性能损失,而不是改善. 为了避免与线程相关的损坏问题,根据需要使用Synchronization构造(例如lock, mutex, semaphore,)非常重要.读取始终是线程安全的,但是写入需要适当的同步.

Also, another issue is thread is a very costly resource, each thread has a thread environment block, Kernel memory allocation. Also for scheduling each thread on a processor core, time is spent for context switching. It is quite possible that misuse can cause huge performance penalty, instead of improvement. To avoid Thread related corruption issues, its important to use the Synchronization constructs, like lock, mutex, semaphore, based on requirement. Read is always thread safe, but Write needs appropriate Synchronization.

线程与线程池?

Thread Vs ThreadPool ?

实际线程不是我们在C#.Net中使用的线程,它只是调用Win32线程的托管包装器.挑战仍然在于用户严重滥用的能力,例如,调用的线程数量超过了所需的数量,分配了处理器亲和力,因此,我们请求一个标准池将工作项及其窗口排入队列以决定何时创建新线程不是更好吗?当已经存在的线程可以计划工作项时,则为必需.线程是一种昂贵的资源,需要在使用上进行优化,否则可能会带来麻烦.

Real threads are not the ones, we use in C#.Net, that's just the managed wrapper to invoke Win32 threads. Challenge remain in user's ability to grossly misuse, like invoking lot more than required number of threads, assigning the processor affinity, so isn't it better that we request a standard pool to queue the work item and its windows which decide when the new thread is required, when an already existing thread can schedule the work item. Thread is a costly resource, which needs to be optimized in usage, else it can be bane not boon.

多线程编程的发展,例如并行API,任务API

Evolution of Multi threaded programming, like Parallel API, Task API

从.Net 4.0开始,用于数据并行化和任务并行化的各种新API Parallel.For,Parallel.ForEach使在系统中引入并发变得非常简单.这些API再次在内部使用线程池工作.任务更像是安排将来某个时间的工作.现在引入并发就像轻而易举,尽管仍然需要同步结构来避免内存损坏,争用条件或线程安全集合.

From .Net 4.0 onward, variety of new APIs Parallel.For, Parallel.ForEach for data paralellization and Task Parallelization, have made it very simple to introduce concurrency in the system. These APIs again work using a Thread pool internally. Task is more like scheduling a work for sometime in the future. Now introducing concurrency is like a breeze, though still synchronization constructs are required to avoid memory corruption, race condition or thread safe collections can be used.

并发收集,用法?

Concurrent Collections, usage ?

ConcurrentBag, ConcurrentQueue, ConcurrentDictionary一样的实现是System.Collections.Concurrent的一部分,它们是固有的线程安全的,使用spin-wait且比显式Synchronization更加容易和快捷.也更容易管理和工作.还有另外一套API,例如ImmutableList System.Collections.Immutable,可通过 nuget 获得,这些线程通过内部创建数据结构的另一个副本的优点.

Implementations like ConcurrentBag, ConcurrentQueue, ConcurrentDictionary, part of System.Collections.Concurrent are inherent thread safe, using spin-wait and much easier and quicker than explicit Synchronization. Also much easier to manage and work. There's another set API like ImmutableList System.Collections.Immutable, available via nuget, which are thread safe by virtue of creating another copy of data structure internally.

异步等待,线程但没有线程,为什么它们最适合IO

Async-Await, thread but no thread, why they are best for IO

这是并发性的一个重要方面,它用于IO调用(磁盘,网络),到目前为止讨论的其他API都用于基于计算的并发性,因此线程很重要并且可以使其更快,但是对于IO调用,线程没有除了等待呼叫返回外使用,IO呼叫在基于硬件的队列IO Completion ports

This is an important aspect of concurrency meant for IO calls (disk, network), other APIs discussed till now, are meant for compute based concurrency so threads are important and make it faster, but for IO calls thread has no use except waiting for the call to return, IO calls are processed on hardware based queue IO Completion ports

这篇关于什么是多线程程序,它如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆