Simple prime number program - Weird issue with threads C#

后端 未结 1 1674
挽巷
挽巷 2021-01-22 21:57

This is my code:

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

namespace FirePrime
{
    class P         


        
相关标签:
1条回答
  • 2021-01-22 22:40

    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 讨论(0)
提交回复
热议问题