开发者

Simple prime number program - Weird issue with threads C#

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;
        }

        st开发者_如何学运维atic 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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜