繁体   English   中英

简单的素数程序-线程C#的奇怪问题

[英]Simple prime number program - Weird issue with threads C#

这是我的代码:

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

这应该是一个非常简单的程序,应该使用并行工作的nrThreads线程查找并输出第一个nrNums质数。

因此,我只是将nrNums拆分为相等的nrThreads块(嗯,最后一个将不相等;如果nrThreads不被nrNums ,那么它当然也将包含其余部分)。

我启动nrThreads线程。

他们都在各自的块中测试每个数字,看是否为质数。 它们将所有内容标记在布尔数组中,从而使所有素数保持一致。

完成后,所有线程都将另一个布尔数组ThreadsFinished的特定元素变为true。

现在,奇怪的部分开始了:

线程永远不会结束。 如果调试,我发现ThreadNr不是我在循环中为其分配的值,而是另一个值。 我猜这是正常的,因为线程是在之后执行的,此时计数器(变量i)已经增加,但是我不明白如何使代码正确。

有人可以帮忙吗?

先感谢您。

PS:我知道算法不是很有效; 我的目标是使用带有x给定螺纹的Eratosthenes筛子的解决方案。 但是到目前为止,我什至无法使它工作,而且我还没有找到任何能以我能理解的语言实现该算法的示例。

线程运行时,该线程接收的值是一个startNum 要解决该问题,请将值复制到局部变量中:

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

代码中的另一个错误正在等待所有线程:

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

一个可以帮助同步线程的技巧:您可以将所有线程保存在列表中,然后从主线程加入它们。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM