Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Мьютексные объекты

Мьютекс аналогичен монитору, он не допускает одновременного выполнения блока кода более чем из одного потока. Название "мьютекс" – сокращенная форма слова "взаимоисключающий" ("mutually exclusive" на английском языке). Впрочем, в отличие от мониторов мьютексы можно использовать для синхронизации потоков по процессам. Мьютекс представляется классом Mutex.

При использовании для синхронизации внутри процесса мьютекс называется именованным мьютексом, поскольку он должен использоваться в другом приложении и к нему нельзя предоставить общий доступ с помощью глобальной или статической переменной. Ему нужно назначить имя, чтобы оба приложения могли получить доступ к одному и тому же объекту мьютекса.

Несмотря на то, что для синхронизации потоков внутри процесса можно использовать мьютекс, рекомендуется использовать Monitor, поскольку мониторы были созданы специально для .NET Framework и более эффективно используют ресурсы. Напротив, класс Mutex является оболочкой для структуры Win32. Мьютекс мощнее монитора, но для мьютекса требуются переходы взаимодействия, на которые затрачивается больше вычислительных ресурсов, чем на обработку класса Monitor.

How to: Create and Terminate Threads

This example demonstrates how an auxiliary or worker thread can be created and used to perform processing in parallel with the primary thread. Making one thread wait for another and gracefully terminating a thread are also demonstrated.

The example creates a class named Worker that contains the method, DoWork, which the worker thread will execute. This is essentially the Main function for the worker thread. The worker thread will begin execution by calling this method, and terminate automatically when this method returns. The DoWork method looks like this:

public void DoWork()

{

while (!_shouldStop)

{

Console.WriteLine("worker thread: working...");

}

Console.WriteLine("worker thread: terminating gracefully.");

}

The Worker class contains an additional method that is used to indicate to DoWork that it should return. This method is named RequestStop, and looks like this:

public void RequestStop()

{

_shouldStop = true;

}

The RequestStop method just assigns the _shouldStop data member to true. Because this data member is checked by the DoWork method, this has the indirect effect of causing DoWork to return, which terminates the worker thread. However, you should notice that DoWork and RequestStop will be executed by different threads. DoWork is executed by the worker thread, and RequestStop is executed by the primary thread, so that the _shouldStop data member is declared volatile, like this:

private volatile bool _shouldStop;

The volatile keyword alerts the compiler that multiple threads will access the _shouldStop data member, and therefore it should not make any optimization assumptions about the state of this member.