# Parallel.For Loop ( Race Condition )

Page 1 of 1

## 0 Replies - 3918 Views - Last Post: 30 August 2012 - 02:34 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=290507&amp;s=eabd7942f1f74712f410c1b3c482b798&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 tang3li2

Reputation: 0
• Posts: 1
• Joined: 30-August 12

# Parallel.For Loop ( Race Condition )

Posted 30 August 2012 - 02:34 PM

hi, i have code that cut and replace if the letters has been found
example i have a word "cat", if i found the letter "a" it will be removed to the word "cat"
so the remaining would be "ct", repeat the process until it will completely done..

so i have created it and already fully functioning in 1 thread..
but when i transfer it on a parallel.for loop, it acts weird, i dig in deeper and i found out that the process is to fast
and it overwrites the variable, so i try the synclock method, but it slows the process.. and i try the interlock but no good it acts weird because it doesnt process the ordering like "1.2.3.4.5", what i want to do is to preserve the speed without using synclock..

so here's the code.

```sqrt = Math.Ceiling(Math.Sqrt(2549))
a = 0
xchar2 = ""

Parallel.For(1, sqrt + 1, Sub(o)
Dim a, b, c, i, y, z As Long
i = 2
a = 0
If o = 1 Then
b = 1
c = sqrt
Else
b = ((o * sqrt ) + 1) - sqrt
c = (o * (sqrt ))
End If
For y = b To c
a = y
tmpChar = "cat"
For z = 0 To i
xmod(z) = a Mod 26
a = ((a - a Mod 26) / 26)
If InStr(tmpChar, numToletter(xmod(z))) = 0 Then
bListed1 = False
Exit For
Else
tmpChar = Mid(tmpChar, 1, InStr(tmpChar, numToletter(xmod(z))) - 1) & Mid(tmpChar, InStr(tmpChar, numToletter(xmod(z))) + 1)
If z = 0 Then
If check2(numToletter(xmod(z))) Then
xchar2 = numToletter(xmod(z))
bListed1 = True
Else
xchar2 = ""
bListed1 = False
Exit For
End If
Else
If check2(numToletter(xmod(z))) Then
xchar2 &= numToletter(xmod(z))
bListed1 = True
Else
xchar2 = ""
bListed1 = False
Exit For
End If
End If
End If
'---
Next
If bListed1 Then
Debug.Print(StrReverse(xchar2))
End If
Next
End Sub)
```

and this is the part where the race condition occur, it produces error that it should be equal to zero or greater than zero, because the variable is less than zero or null ( i guess )

```tmpChar = Mid(tmpChar, 1, InStr(tmpChar, numToletter(xmod(z))) - 1) & Mid(tmpChar, InStr(tmpChar, numToletter(xmod(z))) + 1)
```

i wonder how to implement the Interlocked method here??? i think of it as a preliminary solution, any suggestion guys??

Is This A Good Question/Topic? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }