W
W
wlastas2021-06-04 03:02:14
C++ / C#
wlastas, 2021-06-04 03:02:14

How to implement a Thread safe state object (written in one, read from many)?

Good afternoon
As I understand it, you need to use ReaderWriterLockSlim from here
https://docs.microsoft.com/en-us/dotnet/api/system...
I did everything like they have, crashes with System.NullReferenceException: 'Object reference not set to an instance of an object.'

using System;
    using System.Threading;

    public class Player {
        public int id;
        public override string ToString() {
            return id.ToString();
        }
    }
    public class SlimTest{
        ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
        Random R = new Random();
        Player _leader;
        public Player leader {
            get {
                locker.EnterReadLock();
                try {
                    return _leader;
                }
                finally {
                    locker.ExitReadLock();
                }
            }
        }
        int _id = 0;
        public SlimTest() {
            var main = new Thread(() => {
                while(true) {
                    locker.EnterWriteLock();
                    try {
                        var cf = R.Next(1, 10) % 2;
                        if(cf > 0)
                            _leader = new Player() { id = _id += 1 };
                        else
                            _leader = null;
                    }
                    finally {
                        locker.ExitWriteLock();
                    }
                    Thread.Sleep(R.Next(3, 10));
                }
            });
            main.IsBackground = true;
            main.Start();

            for(int i = 0; i < 10;i++) {
                var reader = new Thread(() => {
                    while(true) {
                        if(leader != null) {
                            Console.Write(leader.id); // <<==System.NullReferenceException: 'Object reference not set to an instance of an object.'
                        }
                        else
                            Console.Write(".");
                        Thread.Sleep(R.Next(3, 10));
                    }
                });
                reader.IsBackground = true;
                reader.Start();
            }
        }
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
none7, 2021-06-04
@wlastas

var tmp_leader = leader;
Console.Write(tmp_leader == null ? "." : tmp_leader.id.ToString());

B
BasiC2k, 2021-06-04
@BasiC2k

Perhaps it makes sense to save all Player s to a thread-safe list and then access it later.
https://professorweb.ru/my/csharp/charp_theory/lev...
In this case, no blocking system is required.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question