Tell me how to organize the synchronization? Judging by the theoretical material, a named mutex, semaphore, or some events can help. I tried to do it, but I don’t understand how. Suppose I have a public resource (let it be the same queue). I want to write a class to work with this queue, which will be used from different processes (on the same machine, of course) and threads. It turned out something like this:
public class Worker<T> where T : class { private const string MUTEX_NAME = "SOME_UNIQUE_NAME"; private Mutex mutex; private Queue<T> queue = new Queue<T>(); public Worker() { try { mutex = Mutex.OpenExisting(MUTEX_NAME); } catch (WaitHandleCannotBeOpenedException ex) { mutex = new Mutex(false, MUTEX_NAME); } } public void Add(T entity) { // check if entity not null mutex.WaitOne(); queue.Enqueue(entity); mutex.ReleaseMutex(); } public T Get() { if (queue.Count == 0) { mutex.WaitOne(); } mutex.ReleaseMutex(); return queue.Dequeue(); } }
I understand that this is non-working nonsense, but I don’t think how to bring it to mind. I use the assumption approximately as follows: one or several processes, within which there will be one or several threads, which will add data to this queue and one process, within which there will be one or several threads, which will read data. Thank.