// Populate the queue. for (int i = 0; i < 10000; i++){ cq.Enqueue(i); }
int result; if (!cq.TryPeek(out result)) { Console.WriteLine("CQ: TryPeek failed when it should have succeeded"); } elseif (result != 0) { Console.WriteLine("CQ: Expected TryPeek result of 0, got {0}", result); } }
Interlock의 예제를 보면 왜 TryDequeue인지, 왜 CPU 사용률이 증가되는지 알 수 있다
staticvoidMain(){ Thread myThread; Random rnd = new Random();
for(int i = 0; i < numThreads; i++){ myThread = new Thread(new ThreadStart(MyThreadProc)); myThread.Name = String.Format("Thread{0}", i + 1); //Wait a random amount of time before starting next thread. Thread.Sleep(rnd.Next(0, 1000)); myThread.Start(); } }
privatestaticvoidMyThreadProc(){ for(int i = 0; i < numThreadIterations; i++){ UseResource(); //Wait 1 second before next attempt. Thread.Sleep(1000); } }
//A simple method that denies reentrancy. staticboolUseResource(){ //0 indicates that the method is not in use. if(0 == Interlocked.Exchange(ref usingResource, 1)){ Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name); //Code to access a resource that is not thread safe would go here. //Simulate some work Thread.Sleep(500);
Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name); //Release the lock Interlocked.Exchange(ref usingResource, 0); returntrue; } else{ Console.WriteLine(" {0} was denied the lock", Thread.CurrentThread.Name); returnfalse; } } } }