zoukankan      html  css  js  c++  java
  • 多线程(临界点处理)

    对于多线程临界点的几种处理方式

    1:   lock
    2:Interlocked.Increment(ref page) ++  ,Interlocked.Decrement(ref page)--
    如下代码,我们执行Page3的时候page输出会等于100或者比100小

    解决方法,用Page或者Page1方法

    public class Program
    {

    static void Main(string[] args)
    {
    for (int num=0;num++<10;) {
    Test test = new Test();
    List<Thread> list = new List<Thread>();
    for (int a = 0; a < 100; a++)
    {
    //var thread = new Thread(test.Page3);
    var thread = new Thread(test.Page1);
    list.Add(thread);
    }
    list.ForEach(x => x.Start());
    list.ForEach(x => x.Join());
    Console.WriteLine(test.page);
    Console.WriteLine("______________");
    }
    Console.ReadKey();
    }

    }

    public class Test
    {

    public ThreadLocal<int> ThreadLocal = new ThreadLocal<int>();
    public int page = 0;
    public void Page(Object obj)
    {

    lock (obj) {
    this.page++;
    }

    }

    public void Page1()
    {

    Interlocked.Increment(ref page);

    }

    public void Page3()
    {
    this.page++;

    }
    }

  • 相关阅读:
    BUG漏测的原因总结,以及如何处理
    费用流
    拉格朗日插值
    数论问题整理
    计数问题
    POJ 1741 Tree
    bzoj 2820: YY的GCD
    luogu P3690 【模板】Link Cut Tree (动态树)
    bzoj 1036: [ZJOI2008]树的统计Count
    bzoj 3282: Tree
  • 原文地址:https://www.cnblogs.com/hq89533921/p/13253867.html
Copyright © 2011-2022 走看看