Threading in windows operating system

Управляемые и неуправляемые потоки в Windows Managed and unmanaged threading in Windows

Управление всеми потоками осуществляется посредством класса Thread , включая потоки, созданные средой CLR или созданные за пределами среды выполнения и входящие в управляемую среду для выполнения кода. Management of all threads is done through the Thread class, including threads created by the common language runtime and those created outside the runtime that enter the managed environment to execute code. Среда выполнения отслеживает в своем процессе все потоки, которые когда-либо выполняли код в управляемой среде. The runtime monitors all the threads in its process that have ever executed code within the managed execution environment. Другие потоки она не отслеживает. It does not track any other threads. Потоки могут входить в управляемую среду выполнения посредством COM-взаимодействия (так как среда выполнения предоставляет управляемые объекты неуправляемой среде в качестве COM-объектов), функции COM DllGetClassObject и вызова неуправляемого кода. Threads can enter the managed execution environment through COM interop (because the runtime exposes managed objects as COM objects to the unmanaged world), the COM DllGetClassObject function, and platform invoke.

Когда неуправляемый поток входит в среду выполнения, например, посредством вызываемой оболочки COM, система проверяет локальное хранилище потока данного потока для поиска внутреннего управляемого объекта Thread . When an unmanaged thread enters the runtime through, for example, a COM callable wrapper, the system checks the thread-local store of that thread to look for an internal managed Thread object. Если он найден, среда выполнения уже оповещена об этом потоке. If one is found, the runtime is already aware of this thread. Если найти объект не удается, среда выполнения создает новый объект Thread и устанавливает его в локальном хранилище потока данного потока. If it cannot find one, however, the runtime builds a new Thread object and installs it in the thread-local store of that thread.

При использовании управляемых потоков Thread.GetHashCode является стабильным средством идентификации управляемого потока. In managed threading, Thread.GetHashCode is the stable managed thread identification. В течение времени существования вашего потока он не будет конфликтовать со значением из любого другого потока независимо от того, из какого домена приложения вы получили это значение. For the lifetime of your thread, it will not collide with the value from any other thread, regardless of the application domain from which you obtain this value.

Сопоставление потоков Win32 с управляемыми потоками Mapping from Win32 threading to managed threading

В следующей таблице элементы потоков Win32 сопоставляются со своими ближайшими аналогами из среды выполнения. The following table maps Win32 threading elements to their approximate runtime equivalent. Обратите внимание, что такое сопоставление не означает идентичную функциональность. Note that this mapping does not represent identical functionality. Например, TerminateThread не выполняет предложения finally , не освобождает ресурсы и не может быть запрещен. For example, TerminateThread does not execute finally clauses or free up resources, and cannot be prevented. Однако Thread.Abort выполняет весь ваш код отката, освобождает все ресурсы и может быть отменен с помощью ResetAbort. However, Thread.Abort executes all your rollback code, reclaims all the resources, and can be denied using ResetAbort. Прежде чем делать предположения о функциональности, тщательно изучите документацию. Be sure to read the documentation closely before making assumptions about functionality.

Читайте также:  Linux сменить пароль другому пользователю
В Win32 In Win32 В среде CLR In the common language runtime
CreateThread CreateThread Сочетание Thread и ThreadStart Combination of Thread and ThreadStart
TerminateThread TerminateThread Thread.Abort
SuspendThread SuspendThread Thread.Suspend
ResumeThread ResumeThread Thread.Resume
Sleep Sleep Thread.Sleep
WaitForSingleObject в дескрипторе потока WaitForSingleObject on the thread handle Thread.Join
ExitThread ExitThread Эквивалент отсутствует No equivalent
GetCurrentThread GetCurrentThread Thread.CurrentThread
SetThreadPriority SetThreadPriority Thread.Priority
Эквивалент отсутствует No equivalent Thread.Name
Эквивалент отсутствует No equivalent Thread.IsBackground
Близко к CoInitializeEx (OLE32.DLL) Close to CoInitializeEx (OLE32.DLL) Thread.ApartmentState

Управляемые потоки и подразделения COM Managed threads and COM apartments

Управляемый поток может быть отмечен для указания того, что в нем будет размещаться однопотоковое или многопотоковое подразделение. A managed thread can be marked to indicate that it will host a single-threaded or multithreaded apartment. (Дополнительные сведения об архитектуре потоков COM см. в статье Processes, Threads, and Apartments (Процессы, потоки и подразделения)). Методы GetApartmentState, SetApartmentState и TrySetApartmentState класса Thread возвращают и назначают состояние подразделения потока. (For more information on the COM threading architecture, see Processes, Threads, and Apartments.) The GetApartmentState, SetApartmentState, and TrySetApartmentState methods of the Thread class return and assign the apartment state of a thread. Если состояние не задано, GetApartmentState возвращает ApartmentState.Unknown. If the state has not been set, GetApartmentState returns ApartmentState.Unknown.

Свойство можно задать, только когда поток находится в состоянии ThreadState.Unstarted ; его можно задать только один раз для потока. The property can be set only when the thread is in the ThreadState.Unstarted state; it can be set only once for a thread.

Если состояние подразделения не задано до запуска потока, этот поток инициализируется в качестве многопотокового подразделения (MTA). If the apartment state is not set before the thread is started, the thread is initialized as a multithreaded apartment (MTA). Поток метода завершения и все потоки, управляемые ThreadPool , являются многопотоковыми подразделениями. The finalizer thread and all threads controlled by ThreadPool are MTA.

Для кода запуска приложения единственный способ управления состоянием подразделения заключается в применении MTAThreadAttribute или STAThreadAttribute к процедуре точки входа. For application startup code, the only way to control apartment state is to apply the MTAThreadAttribute or the STAThreadAttribute to the entry point procedure.

Управляемые объекты, предоставляемые интерфейсу COM, работают так, как если бы они агрегировали упаковщик в режиме свободного потока. Managed objects that are exposed to COM behave as if they had aggregated the free-threaded marshaler. Другими словами, их можно вызвать из любого подразделения COM в режиме свободного потока. In other words, they can be called from any COM apartment in a free-threaded manner. В таком режиме не работают только управляемые объекты, производные от ServicedComponent или StandardOleMarshalObject. The only managed objects that do not exhibit this free-threaded behavior are those objects that derive from ServicedComponent or StandardOleMarshalObject.

В управляемом коде отсутствует поддержка SynchronizationAttribute , если только вы не используете контексты и контекстно-привязанные управляемые экземпляры. In the managed world, there is no support for the SynchronizationAttribute unless you use contexts and context-bound managed instances. Если вы используете корпоративные службы, ваш объект должен быть производным от ServicedComponent (который сам является производным от ContextBoundObject). If you are using Enterprise Services, then your object must derive from ServicedComponent (which is itself derived from ContextBoundObject).

Когда управляемый код вызывает COM-объекты, он всегда следует правилам COM. When managed code calls out to COM objects, it always follows COM rules. Другими словами, он выполняет вызов через прокси-серверы подразделения COM и оболочки контекста COM+ 1.0, как того требует OLE32. In other words, it calls through COM apartment proxies and COM+ 1.0 context wrappers as dictated by OLE32.

Блокирующие проблемы Blocking issues

Если поток выполняет неуправляемый вызов для операционной системы, которая заблокировала этот поток в неуправляемом коде, среда выполнения не берет на себя управление им для Thread.Interrupt или Thread.Abort. If a thread makes an unmanaged call into the operating system that has blocked the thread in unmanaged code, the runtime will not take control of it for Thread.Interrupt or Thread.Abort. В случае с Thread.Abortсреда выполнения помечает поток как Abort и берет управление, когда он повторно входит в управляемый код. In the case of Thread.Abort, the runtime marks the thread for Abort and takes control of it when it re-enters managed code. Вместо неуправляемой блокировки рекомендуется использовать управляемую блокировку. It is preferable for you to use managed blocking rather than unmanaged blocking. WaitHandle.WaitOne,WaitHandle.WaitAny, WaitHandle.WaitAll, Monitor.Enter, Monitor.TryEnter, Thread.Join, GC.WaitForPendingFinalizers и др. реагируют на Thread.Interrupt и Thread.Abort. WaitHandle.WaitOne,WaitHandle.WaitAny, WaitHandle.WaitAll, Monitor.Enter, Monitor.TryEnter, Thread.Join, GC.WaitForPendingFinalizers, and so on are all responsive to Thread.Interrupt and to Thread.Abort. Кроме того, если ваш поток находится в однопотоковом подразделении, все эти операции управляемой блокировки будут корректно выдавать сообщения в ваше подразделение, пока поток находится в заблокированном состоянии. Also, if your thread is in a single-threaded apartment, all these managed blocking operations will correctly pump messages in your apartment while your thread is blocked.

Потоки и волокна Threads and fibers

Потоковая модель .NET не поддерживает волокна. The .NET threading model does not support fibers. Не следует вызывать неуправляемые функции, которые реализуется с использованием волокон. You should not call into any unmanaged function that is implemented by using fibers. Такие вызовы могут привести к сбою среды выполнения .NET. Such calls may result in a crash of the .NET runtime.

Operating System — Multi-Threading

What is Thread?

A thread is a flow of execution through the process code, with its own program counter that keeps track of which instruction to execute next, system registers which hold its current working variables, and a stack which contains the execution history.

A thread shares with its peer threads few information like code segment, data segment and open files. When one thread alters a code segment memory item, all other threads see that.

A thread is also called a lightweight process. Threads provide a way to improve application performance through parallelism. Threads represent a software approach to improving performance of operating system by reducing the overhead thread is equivalent to a classical process.

Each thread belongs to exactly one process and no thread can exist outside a process. Each thread represents a separate flow of control. Threads have been successfully used in implementing network servers and web server. They also provide a suitable foundation for parallel execution of applications on shared memory multiprocessors. The following figure shows the working of a single-threaded and a multithreaded process.

Difference between Process and Thread

S.N. Process Thread
1 Process is heavy weight or resource intensive. Thread is light weight, taking lesser resources than a process.
2 Process switching needs interaction with operating system. Thread switching does not need to interact with operating system.
3 In multiple processing environments, each process executes the same code but has its own memory and file resources. All threads can share same set of open files, child processes.
4 If one process is blocked, then no other process can execute until the first process is unblocked. While one thread is blocked and waiting, a second thread in the same task can run.
5 Multiple processes without using threads use more resources. Multiple threaded processes use fewer resources.
6 In multiple processes each process operates independently of the others. One thread can read, write or change another thread’s data.

Advantages of Thread

  • Threads minimize the context switching time.
  • Use of threads provides concurrency within a process.
  • Efficient communication.
  • It is more economical to create and context switch threads.
  • Threads allow utilization of multiprocessor architectures to a greater scale and efficiency.

Types of Thread

Threads are implemented in following two ways −

User Level Threads − User managed threads.

Kernel Level Threads − Operating System managed threads acting on kernel, an operating system core.

User Level Threads

In this case, the thread management kernel is not aware of the existence of threads. The thread library contains code for creating and destroying threads, for passing message and data between threads, for scheduling thread execution and for saving and restoring thread contexts. The application starts with a single thread.

Advantages

  • Thread switching does not require Kernel mode privileges.
  • User level thread can run on any operating system.
  • Scheduling can be application specific in the user level thread.
  • User level threads are fast to create and manage.

Disadvantages

  • In a typical operating system, most system calls are blocking.
  • Multithreaded application cannot take advantage of multiprocessing.

Kernel Level Threads

In this case, thread management is done by the Kernel. There is no thread management code in the application area. Kernel threads are supported directly by the operating system. Any application can be programmed to be multithreaded. All of the threads within an application are supported within a single process.

The Kernel maintains context information for the process as a whole and for individuals threads within the process. Scheduling by the Kernel is done on a thread basis. The Kernel performs thread creation, scheduling and management in Kernel space. Kernel threads are generally slower to create and manage than the user threads.

Advantages

  • Kernel can simultaneously schedule multiple threads from the same process on multiple processes.
  • If one thread in a process is blocked, the Kernel can schedule another thread of the same process.
  • Kernel routines themselves can be multithreaded.

Disadvantages

  • Kernel threads are generally slower to create and manage than the user threads.
  • Transfer of control from one thread to another within the same process requires a mode switch to the Kernel.

Multithreading Models

Some operating system provide a combined user level thread and Kernel level thread facility. Solaris is a good example of this combined approach. In a combined system, multiple threads within the same application can run in parallel on multiple processors and a blocking system call need not block the entire process. Multithreading models are three types

  • Many to many relationship.
  • Many to one relationship.
  • One to one relationship.

Many to Many Model

The many-to-many model multiplexes any number of user threads onto an equal or smaller number of kernel threads.

The following diagram shows the many-to-many threading model where 6 user level threads are multiplexing with 6 kernel level threads. In this model, developers can create as many user threads as necessary and the corresponding Kernel threads can run in parallel on a multiprocessor machine. This model provides the best accuracy on concurrency and when a thread performs a blocking system call, the kernel can schedule another thread for execution.

Many to One Model

Many-to-one model maps many user level threads to one Kernel-level thread. Thread management is done in user space by the thread library. When thread makes a blocking system call, the entire process will be blocked. Only one thread can access the Kernel at a time, so multiple threads are unable to run in parallel on multiprocessors.

If the user-level thread libraries are implemented in the operating system in such a way that the system does not support them, then the Kernel threads use the many-to-one relationship modes.

One to One Model

There is one-to-one relationship of user-level thread to the kernel-level thread. This model provides more concurrency than the many-to-one model. It also allows another thread to run when a thread makes a blocking system call. It supports multiple threads to execute in parallel on microprocessors.

Disadvantage of this model is that creating user thread requires the corresponding Kernel thread. OS/2, windows NT and windows 2000 use one to one relationship model.

Читайте также:  Windows office 2013 software
Оцените статью