如何将一些信息传递给其他人?

时间:2018-05-21 02:05:19

标签: c#

我有两个主题。如何从thread1获取数据到thread2。这意味着,当thread1完成其工作时,它有一些数据,并且这些数据必须在第二个" thread2"中使用。如何实现它?

这是代码,但该怎么办......现在?

static void Main(string[] args)
        {
            Thread t1 = new Thread(thread1);
            t1.Start();
            Thread t2 = new Thread(thread2);
            t2.Start();
        }
        static void thread1()
        {
                string newstring="123";

        }
        static void thread2()
        {
            //what to do here...what code will be here?
            Console.WriteLine(newstring);
        }

在thread1中可以是任何东西,但我需要得到这个"无论什么",而不是我可以在thread2中使用它

1 个答案:

答案 0 :(得分:2)

两个线程使用的数据必须在两个线程之间共享。

通常称为公共资源。

其中一个你必须注意到你必须在这里实现synchronization

由于两个线程都是独立运行的,并且还在读取/写入公共数据,因此Race Condition的可能性非常高。为了防止这种情况,您必须在读/写数据上实现同步(在公共对象上)。

引用下面的代码,其中CommonResource在两个线程之间是通用的,locking

已实现同步

在您的示例中,一个线程正在写入数据,而其他线程正在读取数据。如果我们不实现同步,则有可能在线程1正在写入新数据时,但线程2(因为它不等待线程1完成它的任务优先)将带来旧数据(或数据无效。)

当有多个线程正在写入数据时情况变得最糟,而不等待其他线程完成写入。

public class CommonResourceClass
{
    object lockObj;
    //Note: here main resource is private 
    //(thus not in scope of any thread)
    string commonString;

    //while prop is public where we have lock
    public string CommonResource
    {
        get
        {
            lock (lockObj)
            {
                Console.WriteLine(DateTime.Now.ToString() + " $$$$$$$$$$$$$$$ Reading");
                Thread.Sleep(1000 * 2); 
                return commonString;
            }
        }
        set
        {
            lock (lockObj)
            {
                Console.WriteLine(DateTime.Now.ToString() + " ************* Writing");
                Thread.Sleep(1000 * 5); 
                commonString = value;
            }
        }
    }

    public CommonResourceClass()
    {
        lockObj = new object();
    }
}

和线程调用就像

    static CommonResourceClass commonResourceClass;
    static void Main(string[] args)
    {
        commonResourceClass = new CommonResourceClass();
        Thread t1 = new Thread(ThreadOneRunner);
        Thread t2 = new Thread(ThreadTwoRunner);
        t1.Start();
        t2.Start();
    }

    static void ThreadOneRunner()
    {
        while(true)
        {
            Console.WriteLine(DateTime.Now.ToString() + " *******Trying To Write");
            commonResourceClass.CommonResource = "Written";
            Console.WriteLine(DateTime.Now.ToString() + " *******Writing Done");
        }
    }

    static void ThreadTwoRunner()
    {
        while(true)
        {
            Console.WriteLine(DateTime.Now.ToString() + " $$$$$$$Trying To Read");
            string Data = commonResourceClass.CommonResource;
            Console.WriteLine(DateTime.Now.ToString() + " $$$$$$$Reading Done");
        }
    }

输出:

enter image description here

注意,读取时间为2秒,写入时间为5秒,因此读取速度应该更快。但如果正在进行写作,阅读必须等到写完。

你可以在输出中清楚地看到,当一个线程试图读取或写入时,当其他线程正在执行它的任务时,它无法做到。

相关问题