1 Replies - 1274 Views - Last Post: 05 July 2012 - 02:05 AM Rate Topic: -----

#1 lucky3  Icon User is offline

  • Friend lucky3 As IHelpable
  • member icon

Reputation: 233
  • View blog
  • Posts: 770
  • Joined: 19-October 11

Data race and adding items to List(Of T) with Parallel.For

Posted 05 July 2012 - 01:37 AM

Hello.

I'm having problem with adding items to list of string, using parallel.for. Obviously so called "data races" occur, and I don't find a solution with google. How can I add all items. I've tried with Interlocked, but couldn't get it to work.


Imports System.Threading.Tasks
Imports System.Threading
Imports System.Collections.Concurrent


Public Class Form1

    Private Sub btnStart_Click(sender As System.Object, e As System.EventArgs) Handles btnStart.Click
        Dim HowManyLoops As Integer = 100000
        Dim objList As New List(Of String)

        Parallel.For(1, HowManyLoops + 1, Sub(m)
                                              If m / 2 = CInt(m / 2) Then

                                                  objList.Add("Pair")
                                              Else
                                                  objList.Add("Odd")
                                              End If
                                          End Sub)

        txtOut.Text = "Number of all elements in list: " & objList.Count & vbNewLine

        Dim Pari As Integer = objList.FindAll(Function(p1) p1 = "Pair").Count
        txtOut.Text &= "Numbr of pair entries: " & Pari & vbNewLine

        Dim NePari As Integer = objList.FindAll(Function(p1) p1 = "Odd").Count
        txtOut.Text &= "Number of odd entries: " & NePari & vbNewLine
    End Sub
End Class






Instead of getting 5000 pairs and 5000 odd entries, I'm getting smaller results. Sometimes it throws "Index was outside the bounds of the array." error. What is proper way to fill list of string with values in parallel.for?

Is This A Good Question/Topic? 0
  • +

Replies To: Data race and adding items to List(Of T) with Parallel.For

#2 lucky3  Icon User is offline

  • Friend lucky3 As IHelpable
  • member icon

Reputation: 233
  • View blog
  • Posts: 770
  • Joined: 19-October 11

Re: Data race and adding items to List(Of T) with Parallel.For

Posted 05 July 2012 - 02:05 AM

I found the solution with ReaderWriterLock.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1