Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 620491
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T18:46:11+00:00 2026-05-13T18:46:11+00:00

I need a mechanism to implement the following scenario: two or more threads need

  • 0

I need a mechanism to implement the following scenario:

  1. two or more threads need to load a given set of values at the same time
  2. only one request must be done per value, so if two threads need to load the same subsets, one must wait for the other
  3. I don’t want to have a lock (or mutex, or another primitive) on each value since they can be potentially too high.

The scenario could be (suppose thread B enters a little bit earlier)

          thread A           thread B
values    5, 8, 9, 12        7, 8, 9, 13, 14
request   5,       12        7, 8, 9, 13, 14
waits for    8, 9
                             >>data loaded<<
retrieves    8, 9

          >> data loaded <<
returns   5, 8, 9, 12

Which concurrent mechanism should I use for this?

Remember a producer/consumer won’t work since thread A and B are not exactly consumers (they are only interested on certain data).

Thanks

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T18:46:12+00:00Added an answer on May 13, 2026 at 6:46 pm

    This sounds much like a lock manager, so why not build one?

    class LockManager<TKey>
    {
        private Dictionary<TKey, List<EventWaitHandle>> locks =
            new Dictionary<TKey, List<EventWaitHandle>>();
        private Object syncRoot = new Object();
    
        public void Lock(TKey key)
        {
            do
            {
                Monitor.Enter(syncRoot);
                List<EventWaitHandle> waiters = null;
                if (true == locks.TryGetValue(key, out waiters))
                {
                    // Key is locked, add ourself to waiting list
                    // Not that this code is not safe under OOM conditions
                    AutoResetEvent eventLockFree = new AutoResetEvent(false);
                    waiters.Add(eventLockFree);
                    Monitor.Exit(syncRoot);
                    // Now wait for a notification
                    eventLockFree.WaitOne();
                }
                else
                {
                    // event is free
                    waiters = new List<EventWaitHandle>();
                    locks.Add(key, waiters);
                    Monitor.Exit(syncRoot);
                    // we're done
                    break;
                }
            } while (true);
    
        }
    
        public void Release(TKey key)
        {
            List<EventWaitHandle> waiters = null;
            lock (syncRoot)
            {
                if (false == locks.TryGetValue(key, out waiters))
                {
                    Debug.Assert(false, "Releasing a bad lock!");
                }
                locks.Remove(key);
            }
            // Notify ALL waiters. Unfair notifications
            // are better than FIFO for reasons of lock convoys
            foreach (EventWaitHandle waitHandle in waiters)
            {
                waitHandle.Set();
            }
        }
    }
    

    You must lock each value before you use it:

    class Program
    {
        class ThreadData
        {
            public LockManager<int> LockManager { get; set; }
            public int[] Work { get; set; }
            public AutoResetEvent Done { get; set; }
        }
    
        static void Main(string[] args)
        {
            int[] forA = new int[] {5, 8, 9, 12};
            int[] forB = new int[] {7, 8, 9, 13, 14 };
    
            LockManager<int> lockManager = new LockManager<int>();
    
            ThreadData tdA = new ThreadData
            {
                LockManager = lockManager,
                Work = forA,
                Done = new AutoResetEvent(false),
            };
            ThreadData tdB = new ThreadData
            {
                LockManager = lockManager,
                Work = forB,
                Done = new AutoResetEvent(false),
            };
    
            ThreadPool.QueueUserWorkItem(new WaitCallback(Worker), tdA);
            ThreadPool.QueueUserWorkItem(new WaitCallback(Worker), tdB);
    
            WaitHandle.WaitAll(new WaitHandle[] { tdA.Done, tdB.Done });
        }
    
        static void Worker(object args)
        {
            Debug.Assert(args is ThreadData);
            ThreadData data = (ThreadData) args;
            try
            {
                foreach (int key in data.Work)
                {
                    data.LockManager.Lock(key);
                    Console.WriteLine("~{0}: {1}",
                        Thread.CurrentThread.ManagedThreadId, key);
                    // simulate the load the set for Key
                    Thread.Sleep(1000);
                }
                foreach (int key in data.Work)
                {
                    // Now free they locked keys
                    data.LockManager.Release(key);
                }
            }
            catch (Exception e)
            {
                Debug.Write(e);
            }
            finally
            {
                data.Done.Set();
            }
        }
    }
    

    The biggest problem you’ll face will be deadlocks. Change the two arrays to {5,8,9,7} and {7,8,9,5} and you’ll see my point immedteatly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am learning and using Web API and need to implement following Authentication mechanism
I need to implement a mechanism of highlighting duplicated values. Values are edited through
I need to implement some form of communication mechanism in my application, to send
I need to implement a very specific demo mechanism. It must not expire after
I need some suggestions for how to implement a very basic mechanism that logs
I need to implement a firmware upgrade mechanism where Apache ACE will be used
I need to implement a mechanism where I can initialize a vector of my
I need ideas to implement a (really) high performance in-memory Database/Storage Mechanism in Java.
I need ideas to implement a (really) high performance in-memory Database/Storage Mechanism. In the
I'm developing a Mac Application in which i need to implement IPC Mechanism. The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.