访问共享列表时的多线程问题

时间:2018-12-07 04:48:28

标签: c# multithreading .net-core

下面的伪代码创建一个“老板”类,该类跟踪并允许与“工人”进行交互。

每个工作程序都是一个线程,并且能够通过使用委托检查其他工作程序的属性来回调到调用的类/线程。

1)CheckString方法线程是否安全,并且在这样的线程之间使用委托有任何问题吗?

2)CheckString是否在worker线程的WorkerBoss线程下运行?

class Worker
{
    private readonly Thread thread;
    public string CurrentString = "";

    public Worker(Action<string> CheckString)
    {
        thread = new Thread(() =>
        {
            while (true)
            {
                // Get random string
                CurrentString = GenerateRandomString();

                // Check random string against other workers
                if (CheckString(CurrentString))
                    Console.WriteLine("Other worker has this string!");
            }
        });
    }
}

class WorkerBoss
{
    private readonly ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();
    public List<Worker> _workers = null;

    public WorkerBoss()
    {
        // Start 10 workers
        for (int i = 0; i < 10; i++)
            _workers.Add(new Worker(CheckString));
    }

    public bool CheckString(string textToCheck)
    {
        _locker.EnterWriteLock();
        try
        {
            // Iterate over workers and see if someone has this string
            foreach (var worker in _workers)
                if (worker.CurrentString == textToCheck)
                    return true;

        return false;
        }
        finally
        {
            _locker.ExitWriteLock();
        }
    }
}

0 个答案:

没有答案