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 8460839
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T13:42:59+00:00 2026-06-10T13:42:59+00:00

I have to shuffle an array by swapping random index elements in parallel. My

  • 0

I have to shuffle an array by swapping random index elements in parallel.
My question is how to prevent other threads from reading and writing elements that are currently being swapped by another thread. I don’t want to lock the entire array while one thread is swapping.

I would like to let couple threads swapping different pairs o elements in the same time.

I tried something like this :

        object[] lockArray = new object[array.Length];
        for (int i = 0; i < array.Length; i++)
            lockArray[i] = new object();

        for (int i = 0; i < thredCount; i++)
        {
            Thread t = new Thread(th => Shuffle.Shuflle(array,lockArray));
            t.Start();
        }

        public class Shuffle
        {
            public static void Shuflle(char[] array,object [] lockArray)
            {
                    for (int count = array.Length - 1; count > 1; count--)
                    {
                        Random rand = new Random();
                        int y = rand.Next(count) + 1;

                        lock (lockArray[count])
                        {
                            lock (lockArray[y])
                            {
                                char temp = array[count];
                                array[count] = array[y];
                                array[y] = temp;
                            }
                        }


                    }
            }
        }

In the array there are digits as chars from 0 to 9,
the result is reordered digits.
But sometimes I get result with one doubled ex. 138952469. 9 is now doubled in shuffled array and 7 is missing.

Please help me diagnose the problem.

  • 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-06-10T13:43:00+00:00Added an answer on June 10, 2026 at 1:43 pm

    What about not using locks at all:

    private void OptimisticalSwap(object[] arr, int i, int j, object sentinel, SpinWait spinWait)
    {
      Interlocked.Increment(ref nSwap);
      if(i == j) return;
      var vi = ExchangeWithSentinel(arr, i, sentinel, spinWait);
      var vj = ExchangeWithSentinel(arr, j, sentinel, spinWait);
      Interlocked.Exchange(ref arr[i], vj);
      Interlocked.Exchange(ref arr[j], vi);
    }
    
    private object ExchangeWithSentinel(object[] arr, int i, object sentinel, SpinWait spinWait)
    {
      spinWait.Reset();
      while(true) {
        var vi = Interlocked.Exchange(ref arr[i], sentinel);
        if(vi != sentinel) return vi;
        spinWait.SpinOnce();
      }
    }
    

    the sentinel is just some dummy object that is shared between all the threads doing swapping and used to “reserve” a position for swapping.

    var sentinel = new object();
    

    The runs result on my laptop (i7):

    Run 0 took 272ms (nSwap=799984, nConflict=300)
    Run 1 took 212ms (nSwap=799984, nConflict=706)
    Run 2 took 237ms (nSwap=799984, nConflict=211)
    Run 3 took 206ms (nSwap=799984, nConflict=633)
    Run 4 took 228ms (nSwap=799984, nConflict=350)
    

    The nConflict is the number of times the swap fails to reserve the position. It is rather low compared to the total number of swaps, so I optimized the routine for the case where there is no conflict only calling the SpinUntil when the conflict occurs.

    The whole code I tested against:

    [TestClass]
      public class ParallelShuffle
      {
        private int nSwap = 0;
        private int nConflict = 0;
        [TestMethod]
        public void Test()
        {
          const int size = 100000;
          const int thCount = 8;
          var sentinel = new object();
          var array = new object[size];
    
          for(int i = 0; i < array.Length; i++)
            array[i] = i;
    
          for(var nRun = 0; nRun < 10; ++nRun) {
            nConflict = 0;
            nSwap = 0;
            var sw = Stopwatch.StartNew();
            var tasks = new Task[thCount];
            for(int i = 0; i < thCount; ++i) {
              tasks[i] = Task.Factory.StartNew(() => {
                var rand = new Random();
                var spinWait = new SpinWait();
                for(var count = array.Length - 1; count > 1; count--) {
                  var y = rand.Next(count);
                  OptimisticalSwap(array, count, y, sentinel, spinWait);
                }
              }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
            }
    
            Task.WaitAll(tasks);
    
            //Console.WriteLine(String.Join(", ", array));
            Console.WriteLine("Run {3} took {0}ms (nSwap={1}, nConflict={2})", sw.ElapsedMilliseconds, nSwap, nConflict, nRun);
            // check for doubles:
            var checkArray = new bool[size];
            for(var i = 0; i < array.Length; ++i) {
              var value = (int) array[i];
              Assert.IsFalse(checkArray[value], "A double! (at {0} = {1})", i, value);
              checkArray[value] = true;
            }
          }
        }
    
    
       private void OptimisticalSwap(object[] arr, int i, int j, object sentinel, SpinWait spinWait)
        {
          Interlocked.Increment(ref nSwap);
          if(i == j) return;
          var vi = ExchangeWithSentinel(arr, i, sentinel, spinWait);
          var vj = ExchangeWithSentinel(arr, j, sentinel, spinWait);
          Interlocked.Exchange(ref arr[i], vj);
          Interlocked.Exchange(ref arr[j], vi);
        }
    
        private object ExchangeWithSentinel(object[] arr, int i, object sentinel, SpinWait spinWait)
        {
          spinWait.Reset();
          while(true) {
            var vi = Interlocked.Exchange(ref arr[i], sentinel);
            if(vi != sentinel) return vi;
            spinWait.SpinOnce();
          }
        }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have array of countries. I want to pick 5 random countries from my
I have a simple page that loads a random image from an array and
I have an array of indices [1 ... 20]. The first 4 elements of
I have the following code- <?php $input = array(); for($i=0; $i<15; $i++) $input[]=$i; shuffle($input);
I have an array coming from my database I want to format and display
I have an array of filenames gathered from a folder as follows: $g =
Possible Duplicate: Get random item from array I need a code to set a
I have looked at Randomize or shuffle an array Randomize or shuffle an array
I have an function that creates an array of words from a string, counts
I have an array of records from a database (although the database is irrelevant

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.