parallel foreach loop - odd behavior

前端 未结 1 1750
梦如初夏
梦如初夏 2020-12-16 20:38

The code below simply creates a List> of random numbers and then calculates the cumulative sum of each list in a parallel foreach loop. Why do I get less than \'numLists\' e

相关标签:
1条回答
  • 2020-12-16 21:00

    List<T> is indeed not thread safe, so cumsupDataP.Add(...) is dropping data in unpredictable ways.

    Replace that line with:

    ConcurrentBag<List<double>> cumsumDataP = new ConcurrentBag<List<double>>();
    

    and it will all work. Note that ConcurrentBag<T> is unordered, but that is fine because you have no way of predicting the order from the threads anyway ;p

    0 讨论(0)
提交回复
热议问题