Jump to content
UBot Underground

Info: Biggest mistake with threading


Recommended Posts

Hi Guys,

 

this is mainly for everyone who just started with threading. But there is one error I have seen a couple of times.

 

Let's say you want to loop through a list and then process the list item in a separated thread.

 

WRONG Way of doing it:

set(#counter,1,"Global")

loop(10) {
    thread {
        TestThread(#counter)
    }
    increment(#counter)
}

 

define TestThread(#row) {
          comment("CODE")
}


This is a timing problem. When you do it like that, the increment command will sometimes increase the global #counter variable, before the thread has received the data.
So instead of:
1-2-3-4-5-6-7-8-9-10
You will end up with something like:
1-3-3-4-5-6-6-8-8-10

So it will mess up the whole thing. 

There are now multiple ways of "fixing" this. 

You could add a wait before the increment to slow everything down. This could work if your threads run long enough. But for very quick stuff, this would slow the whole thing down.

A better approach is:

set(#counter,0,"Global")
loop(10) {
    TestThread(#counter)
    increment(#counter)
}

define TestThread(#row) {
    thread {
          comment("CODE")
    }
}


Hope this will help some of you. Because this threading stuff can be tricky to troubleshoot sometimes. 


Dan

  • Like 2
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...