当前位置: 移动技术网 > IT编程>开发语言>c# > C#使用Interlocked实现线程同步

C#使用Interlocked实现线程同步

2019年07月18日  | 移动技术网IT编程  | 我要评论

通过system.threading命名空间的interlocked类控制计数器,从而实现进程 的同步。iterlocked类的部分方法如下表:

示例,同时开启两个线程,一个写入数据,一个读出数据

代码如下:(但是运行结果却不是我们想象的那样)

using system;
using system.threading;
namespace 线程同步
{
  class program
  {
    static void main(string[] args)
    {
      //缓冲区,只能容纳一个字符
      char buffer = ',';
      string str = ""这里面的字会一个一个读取出来,一个都不会少,,,"";
      //线程:写入数据
      thread writer = new thread(() =>
      {
        for (int i = 0; i < str.length; i++)
        {
          buffer = str[i];
          thread.sleep(20);
        }
      }       
      );
      //线程:读出数据
      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();
    }
  }
}

运行结果图:(每次运行结果都不一样) 

修改代码如下:

using system;
using system.threading;
namespace 线程同步
{
  class program
  {
    //缓冲区,只能容纳一个字符
    private static char buffer;
    //标识量(缓冲区中已使用的空间,初始值为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++)
        {
          //写入数据前检查缓冲区是否已满
          //如果已满,就进行等待,直到缓冲区中的数据被进程reader读取为止
          while (interlocked.read(ref numberofusedspace) == 1)
          {
            thread.sleep(50);
          }
          buffer = str[i];  //向缓冲区写入数据
          //写入数据后把缓冲区标记为满(由0变为1)
          interlocked.increment(ref numberofusedspace);
        }
      });
      //线程:读出者
      thread reader = new thread(delegate ()
      {
        for (int i = 0; i < 24; i++)
        {
          //读取数据前检查缓冲区是否为空
          //如果为空,就进行等待,直到进程writer向缓冲区中写入数据为止
          while (interlocked.read(ref numberofusedspace) == 0)
          {
            thread.sleep(50);
          }
          char ch = buffer;    //从缓冲区读取数据
          console.write(ch);
          interlocked.decrement(ref numberofusedspace);
        }
      });
      //启动线程
      writer.start();
      reader.start();
      console.readkey();
    }
  }
}

正确结果图:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网