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

  • Home
  • SEARCH
  • 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 3665614
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T01:46:56+00:00 2026-05-19T01:46:56+00:00

This is my code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading;

  • 0

This is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace FirePrime
{
    class Program
    {
        static bool[] ThreadsFinished;
        static bool[] nums;

        static bool AllThreadsFinished()
        {
            bool allThreadsFinished = false;
            foreach (var threadFinished in ThreadsFinished)
            {
                allThreadsFinished &= threadFinished;
            }
            return allThreadsFinished;
        }

        static bool isPrime(int n)
        {
            if (n < 2) { return false; }
            if (n == 2) { return true; }
            if (n % 2 == 0) { return false; }
            int d = 3;
            while (d * d <= n)
            {
                if (n % d == 0) { return false; }
                d += 2;
            }
            return true;
        }

        static void MarkPrimes(int startNumber,int stopNumber,int ThreadNr)
        {
            for (int j = startNumber; j < stopNumber; j++)
                nums[j] = isPrime(j);
            lock (typeof(Program))
            {
                ThreadsFinished[ThreadNr] = true;
            }
        }

        static void Main(string[] args)
        {
            int nrNums = 100;
            int nrThreads = 10;
            //var threadStartNums = new List<int>();

            ThreadsFinished = new bool[nrThreads];

            nums = new bool[nrNums];
            //var nums = new List<bool>();
            nums[0] = false;
            nums[1] = false;
            for(int i=2;i<nrNums;i++)
                nums[i] = true;

            int interval = (int)(nrNums / nrThreads);
            //threadStartNums.Add(2);
            //int aux = firstStartNum;
            //int i = 2;
            //while (aux < interval)
            //{
            //    aux = interval*i;
            //    i=i+1;
            //    threadStartNums.Add(aux);
            //}

            int startNum = 0;

            for (int i = 0; i < nrThreads; i++)
            {

                var _thread = new System.Threading.Thread(() => MarkPrimes(startNum, Math.Min(startNum + interval, nrNums), i));
                startNum = startNum + interval;
                //set the thread to run in the background
                _thread.IsBackground = true;
                //start our thread
                _thread.Start();
            }

            while (!AllThreadsFinished())
            {
                Thread.Sleep(1);
            }

            for (int i = 0; i < nrNums; i++)
                if(nums[i])
                    Console.WriteLine(i);
        }
    }
}

This should be a pretty simple program that is supposed to find and output the first nrNums prime numbers using nrThreads threads working in parallel.

So, I just split nrNums into nrThreads equal chunks (well, the last one won’t be equal; if nrThreads doesn’t divide by nrNums, it will also contain the remainder, of course).

I start nrThreads threads.

They all test each number in their respective chunk and see if it is prime or not; they mark everything out in a bool array that keeps a tab on all the primes.

The threads all turn a specific element in another boolean array ThreadsFinished to true when they finish.

Now the weird part begins:

The threads never all end. If I debug, I find that ThreadNr is not what I assign to it in the loop but another value.
I guess this is normal since the threads execute afterwards and the counter (the variable i) is already increased by then but I cannot understand how to make the code be right.

Can anyone help?

Thank you in advance.

P.S.: I know the algorithm is not very efficient; I am aiming at a solution using the sieve of Eratosthenes also with x given threads. But for now I can’t even get this one to work and I haven’t found any examples of any implementations of that algorithm anywhere in a language that I can understand.

  • 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-19T01:46:57+00:00Added an answer on May 19, 2026 at 1:46 am

    The value the thread receives is the one startNum holds when the thread runs. To solve it copy the value into a local variable:

    for (int i = 0; i < nrThreads; i++)
    {
     var localStartNum = startNum; // save value in local variable
                                      // and use in the thread start
        var localIndex = i;
    
     var _thread = new System.Threading.Thread(() => 
                          MarkPrimes(localStartNum,
                                     Math.Min(localStartNum + interval, nrNums),
                                     localIndex));
     startNum = startNum + interval;
     _thread.IsBackground = true;
     _thread.Start();
    }
    

    Another bug in the code is waiting for all threads:

    static bool AllThreadsFinished()
    {
        bool allThreadsFinished = true; // Initialize to true instead of false
                                        // Otherwise, all ANDs will result false
        foreach (var threadFinished in ThreadsFinished)
        {
            allThreadsFinished = threadFinished;
        }
    
        return allThreadsFinished;
    }
    

    One tip which can help a little in synchronizing the threads: You can save all the threads in a list and join them from main thread.

    var threads = new List<Thread>();
    
    for (int i = 0; i < nrThreads; i++)
    {
     var localStartNum = startNum; // save value in local variable
                                      // and use in the thread start
     var _thread = new System.Threading.Thread(() => 
                          MarkPrimes(localStartNum,
                                     Math.Min(localStartNum + interval, nrNums), i));
     startNum = startNum + interval;
     _thread.IsBackground = true;
     _thread.Start();
        threads.Add(_thread);
    }
    
    foreach(var thread in threads)
    {
        thread.Join();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

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.