標籤:ram get dsp space code moni number har runtime
通過互鎖來掌握同步的程式設計
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { private static char buffer; private static long numberOfUsedSpace = 0; static void Main(string[] args) { Thread writer = new Thread(delegate() { string sentence = "無可奈何花落去,似曾相識燕歸來,小園香徑獨徘徊"; for(int i=0;i<24;i++) { while (Interlocked.Read(ref numberOfUsedSpace) == 1) { Thread.Sleep(10); } buffer = sentence[i]; Interlocked.Increment(ref numberOfUsedSpace); } }); Thread Reader = new Thread(delegate() { for(int i=0;i<24;i++) { while (Interlocked.Read(ref numberOfUsedSpace) == 0) { Thread.Sleep(10); } char ch = buffer; Console.Write(ch); Interlocked.Decrement(ref numberOfUsedSpace); } }); writer.Start(); Reader.Start(); } } }
學習掌握Lock語句來實現線程的同步
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { private static char buffer; private static object lockForBuffer = new object(); static void Main(string[] args) { Thread writer = new Thread(delegate() { string sentence = "無可奈何花落去,似曾相識燕歸來,小園香徑獨徘徊"; for(int i=0;i<24;i++) { lock(lockForBuffer) { buffer = sentence[i]; Monitor.Pulse(lockForBuffer); Monitor.Wait(lockForBuffer); } } }); Thread Reader = new Thread(delegate() { for(int i=0;i<24;i++) { lock (lockForBuffer) { char ch = buffer; Console.Write(ch); Monitor.Pulse(lockForBuffer); Monitor.Wait(lockForBuffer); } } }); writer.Start(); Reader.Start(); } } }
using System;using System.Collections.Generic;using System.Diagnostics;using System.Linq;using System.Runtime.InteropServices;using System.Text;using System.Threading;namespace ConsoleApplication1{ class Program { private static object knife = new object(); private static object fork = new object(); static void Main(string[] args) { Thread GirlThread = new Thread(delegate() { Console.WriteLine("今天的月亮好美啊"); lock (knife) { GetKnife(); lock(fork) { GetFork(); Eat(); Console.WriteLine("女孩放下叉子"); Monitor.Pulse(fork); } Console.WriteLine("女孩放下刀子"); Monitor.Pulse(knife); } }); GirlThread.Name = "女孩"; Thread BoyThread = new Thread(delegate() { Console.WriteLine("\n你更美"); lock (knife) { GetKnife(); lock (fork) { GetFork(); Eat(); Console.WriteLine("男孩放下叉子"); Monitor.Pulse(fork); } Console.WriteLine("南海放下刀子"); Monitor.Pulse(knife); } }); BoyThread.Name = "男孩"; GirlThread.Start(); BoyThread.Start(); } static void GetKnife() { Console.WriteLine(Thread.CurrentThread.Name+"拿起刀子"); } static void GetFork() { Console.WriteLine(Thread.CurrentThread.Name + "拿起叉子"); } static void Eat() { Console.WriteLine(Thread.CurrentThread.Name + "吃東西"); } } }
C#線程同步