国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#使用Interlocked實現(xiàn)線程同步

2020-01-24 00:13:21
字體:
供稿:網(wǎng)友

通過System.Threading命名空間的Interlocked類控制計數(shù)器,從而實現(xiàn)進程 的同步。Iterlocked類的部分方法如下表:

示例,同時開啟兩個線程,一個寫入數(shù)據(jù),一個讀出數(shù)據(jù)

代碼如下:(但是運行結(jié)果卻不是我們想象的那樣)

using System;using System.Threading;namespace 線程同步{  class Program  {    static void Main(string[] args)    {      //緩沖區(qū),只能容納一個字符      char buffer = ',';      string str = ""這里面的字會一個一個讀取出來,一個都不會少,,,"";      //線程:寫入數(shù)據(jù)      Thread writer = new Thread(() =>      {        for (int i = 0; i < str.Length; i++)        {          buffer = str[i];          Thread.Sleep(20);        }      }             );      //線程:讀出數(shù)據(jù)      Thread Reader = new Thread(() =>      {        for (int i = 0; i < str.Length; i++)        {          char chartemp = buffer;          Console.Write(chartemp);          Thread.Sleep(30);        }      }      );      writer.Start();      Reader.Start();      Console.ReadKey();    }  }}

運行結(jié)果圖:(每次運行結(jié)果都不一樣) 

修改代碼如下:

using System;using System.Threading;namespace 線程同步{  class Program  {    //緩沖區(qū),只能容納一個字符    private static char buffer;    //標識量(緩沖區(qū)中已使用的空間,初始值為0)    private static long numberOfUsedSpace = 0;    static void Main(string[] args)    {      //線程:寫入者      Thread Writer = new Thread(delegate ()      {        string str = "這里面的字會一個一個讀取出來,一個都不會少,,,";        for (int i = 0; i < 24; i++)        {          //寫入數(shù)據(jù)前檢查緩沖區(qū)是否已滿          //如果已滿,就進行等待,直到緩沖區(qū)中的數(shù)據(jù)被進程Reader讀取為止          while (Interlocked.Read(ref numberOfUsedSpace) == 1)          {            Thread.Sleep(50);          }          buffer = str[i];  //向緩沖區(qū)寫入數(shù)據(jù)          //寫入數(shù)據(jù)后把緩沖區(qū)標記為滿(由0變?yōu)?)          Interlocked.Increment(ref numberOfUsedSpace);        }      });      //線程:讀出者      Thread Reader = new Thread(delegate ()      {        for (int i = 0; i < 24; i++)        {          //讀取數(shù)據(jù)前檢查緩沖區(qū)是否為空          //如果為空,就進行等待,直到進程Writer向緩沖區(qū)中寫入數(shù)據(jù)為止          while (Interlocked.Read(ref numberOfUsedSpace) == 0)          {            Thread.Sleep(50);          }          char ch = buffer;    //從緩沖區(qū)讀取數(shù)據(jù)          Console.Write(ch);          Interlocked.Decrement(ref numberOfUsedSpace);        }      });      //啟動線程      Writer.Start();      Reader.Start();      Console.ReadKey();    }  }}

正確結(jié)果圖:

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對武林網(wǎng)的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 惠水县| 桂林市| 涿州市| 楚雄市| 房产| 同江市| 尉犁县| 十堰市| 临邑县| 策勒县| 青浦区| 策勒县| 丰都县| 阿勒泰市| 黄石市| 涪陵区| 临西县| 桐柏县| 宜黄县| 光山县| 岑溪市| 潼南县| 潞西市| 泽库县| 华阴市| 分宜县| 盐津县| 沂水县| 和龙市| 邛崃市| 景宁| 鄢陵县| 西乌珠穆沁旗| 望城县| 嘉黎县| 格尔木市| 喀喇沁旗| 博客| 台中县| 宜州市| 左云县|