2

Take the following code as an example, simplified so ignore the fact the data is null:

    ConcurrentBag<object> _mySharedData;
    bool _stop = false;

    public void SetThreads()
    {
        foreach(var item in _mySharedData)
        {
            Task.Factory.StartNew((state) => {
                while (!_stop)
                    DoStuffWithItemAsReference(item);
            }, TaskCreationOptions.LongRunning);
        }
    }

The shared data holds a collection of settings, each one corresponding to what is running in that thread. The issue however, is that sometimes they need to look at the settings for the other threads too. Is the code thread safe as long as I add a lock? If settings are updated for a thread from within another thread, how does that work? Because now we have a thread that has a reference to an item in the _mySharedData collection, is it safe to alter its properties?

Thanks

Trent Sartain
  • 446
  • 2
  • 10
Fred Johnson
  • 2,539
  • 3
  • 26
  • 52
  • The concurrent bag makes altering/reading the collection safe, but that use of stop is not safe. You need to lock anything that reads or changes stop – pquest Dec 20 '15 at 21:32
  • Ah nice save. Is there any concurrent version for a single type or am I stuck with lock – Fred Johnson Dec 20 '15 at 21:34
  • I would suggest using a [ManualResetEvent](https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) instead of a bool for that. – pquest Dec 20 '15 at 21:36
  • 1
    Using `volatile bool` should be enough for this kind of use to be thread safe. – Medo42 Dec 20 '15 at 21:39
  • Note that your use of `item` in that `foreach` loop is wrong in C# versions prior to 5.0, because old C# versions would actually use only one variable `item` and update it for each iteration. See here for more details of what that means: http://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach – Medo42 Dec 20 '15 at 21:46

1 Answers1

2

ConcurrentBag is thread safe you don't need to lock that.

If settings are shared between two objects within mySharedData such as sharing a list, you will need to make sure that is a thread safe collection or do locking if it is another reference type.

Xela
  • 2,322
  • 1
  • 17
  • 32