Ahmadali Shafiee
Ahmadali Shafiee

Reputation: 4657

Index was out of range thrown but index was not really out of range

I'm working on multithread program and I want to check that all threads all finished then I have a global List<bool> tr and when I create a new thread I add a false to it and at the end of the thread I make it true by passing the index of current thread's bool in list to thread.

This is the loop that I start the treads on it:

for (int i = 0; i < t; i++)
{
    int n = int.Parse(r.ReadLine());
    List<int> nums = (from s in r.ReadLine().Split(' ') select int.Parse(s)).ToList();
    tr.Add(false);
    new Thread(() => Process(nums, i)).Start();
}

and this is Process method:

public static void Process(List<int> Data, int tNum)
{
    output.Add(ProcessSums(ProcessSubs(Data)).Distinct().Count());
    tr[tNum] = true;
}

the problem is in one of the threads, when tr[tNum] = true; whats to run it throws ArgumentOutOfRangeException and says the Index was out of range. but the length of tr is 97 and the index is 95. I don't know what the problem is but I really need help. Can anybody help me?!?

Upvotes: 2

Views: 506

Answers (1)

paparazzo
paparazzo

Reputation: 45096

If this does not work please just comment and I will delete rather than marking it down as it is too much for a comment and I did not test but I think it is really as easy as Daniel's comment

source

int i=0;
Parallel.For (0, t-1, i,=>
{
    int n = int.Parse(r.ReadLine());
    List<int> nums = (from s in r.ReadLine().Split(' ') select int.Parse(s)).ToList();
    Process(nums, i);
});

Upvotes: 1

Related Questions