跨锁定的2个线程共享数据模型

时间:2014-01-20 20:47:31

标签: c# multithreading thread-safety

Hello社区我想知道是否有人可以参与以下代码。为了给出一些上下文,我目前有一个要求,即我将1个类用作跨多个线程的共享数据模型。这是Datamodel类。

public class A {

        public int num1 = 0;

    }

    public class DataModel {

        private readonly object locker = new object();
        private int num1 = 0;
        private A classA = new A();

        public object Locker {
            get {
                return locker;
            }
        }

        public int Num1 {
            get {
                return num1;
            }
            set {
                num1 = value;
            }
        }


        public A ClassA {

            get{

                return classA;

            }set{

                classA = value;

            }
        }

    }

以下是一些测试线程安全性的示例代码。

public partial class Form1 : Form {

        DataModel sharedData = new DataModel();

        Thread thread1;
        Thread thread2;

        public Form1() {

            InitializeComponent();

            if (thread1 != null) {
                thread1.Abort();
                thread1.Join();
            }

            thread1 = new Thread(new ThreadStart(Thread1Func));
            thread1.Name = "Thread 1";
            thread1.Start();


            if (thread2 != null) {
                thread2.Abort();
                thread2.Join();
            }

            thread2 = new Thread(new ThreadStart(Thread2Func));
            thread2.Name = "Thread 2";
            thread2.Start();

        }

        private void Thread1Func() {

            while (true) {

                lock (sharedData.Locker) {

                    int num1Value = sharedData.Num1;
                    num1Value = (num1Value < int.MaxValue) ? (num1Value + 1) : (num1Value = 0);
                    sharedData.Num1 = num1Value;
                    sharedData.ClassA.num1 = num1Value;
                    Console.WriteLine("sharedData.Num1 {0} sharedData.ClassA.num1 {1}", sharedData.Num1, sharedData.ClassA.num1);
                }

                Thread.Sleep(100);

            }

        }

        private void Thread2Func() {

            while (true) {

                lock (sharedData.Locker) {

                    int num2Value = sharedData.Num1;
                    num2Value = (num2Value < int.MaxValue) ? (num2Value + 5) : (num2Value = 0);
                    sharedData.Num1 = num2Value;
                    sharedData.ClassA.num1 = num2Value;
                    Console.WriteLine("sharedData.Num1 {0} sharedData.ClassA.num1 {1}", sharedData.Num1, sharedData.ClassA.num1);

                }

                Thread.Sleep(100);

            }


        }


    }

在这段代码中,我使用“Locker”变量锁定Datamodel类,然后继续读取数据并设置数据。我的问题是,这是一种在多于1个线程使用时确保线程安全类的正确方法吗?

提前感谢您的反馈意见。

0 个答案:

没有答案