标签:seconds tle data- tin stop 其它 安全 sel 运行
valatile关键字指示一个字段可能被同时执行的多个线程修改。出于性能原因,编译器,运行时系统甚至硬件可能重新安排对内存位置的读取和写入。声明为valatile的字段不受这些优化的约束。添加volatile修饰符可确保所有线程将按照执行顺序对其它任何线程执行的volatile写入进行观察,从执行的所有线程来看,不能保证valatile写入的整体顺序。
volatile关键字可以应用于以下类型的字段:
引用类型。
指针类型(在不安全的上下文中)。请注意,尽管指针本身可以是易失性的,但其指向的对象却不能。换句话说,您不能声明“ volatile的指针”。
简单类型,例如sbyte,byte,short,ushort,int,uint,char,float和bool。
具有以下基本类型之一的枚举类型:byte,sbyte,short,ushort,int或uint。 通用类型参数已知为引用类型。
其他类型(包括double和long)不能标记为volatile,因为不能保证对这些类型的字段进行读写。若要保护对这些类型的字段的多线程访问,请使用Interlocked类成员或使用lock语句保护访问
注意:volatile关键字只能应用于类(class)或结构(struct)的字段。局部变量不能声明为volatile。
下面的示例演示如何将公共字段变量声明为volatile。
class VolatileTest { public volatile int sharedStorage; public void Test(int _i) { sharedStorage = _i; } }
下面的示例演示如何创建辅助线程(auxiliray thread 或者较 worker thread ),以及如何使用该辅助线程与主线程并行执行处理。有关多线程的更多信息,请参见托管线程(Managed Threading)
public class Worker { // This method is called when the thread is started. public void DoWork() { bool work = false; while (!_shouldStop) { work = !work; // simulate some work } Console.WriteLine("Worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Keyword volatile is used as a hint to the compiler that this data // member is accessed by multiple threads. private volatile bool _shouldStop; } public class WorkerThreadExample { public static void Main() { // Create the worker thread object. This does not start the thread. Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork); // Start the worker thread. workerThread.Start(); Console.WriteLine("Main thread: starting worker thread..."); // Loop until the worker thread activates. while (!workerThread.IsAlive) ; // Put the main thread to sleep for 500 milliseconds to // allow the worker thread to do some work. Thread.Sleep(500); // Request that the worker thread stop itself. workerObject.RequestStop(); // Use the Thread.Join method to block the current thread // until the object‘s thread terminates. workerThread.Join(); Console.WriteLine("Main thread: worker thread has terminated."); } // Sample output: // Main thread: starting worker thread... // Worker thread: terminating gracefully. // Main thread: worker thread has terminated. }
标签:seconds tle data- tin stop 其它 安全 sel 运行
原文地址:https://www.cnblogs.com/sy-liu/p/13084078.html