This is a read-only archive of the old Scratch 1.x Forums.
Try searching the current Scratch discussion forums.

#1 2011-07-14 16:46:25

andrew_webster
New Scratcher
Registered: 2011-06-09
Posts: 8

race conditions

Here is the scenario: two sprites are moving towards each other with random pauses(move 10 steps, wait (pick random 0.1 to 0.5) ).  If the objects are touching, each has a script that tells it to reset its position.

In an ideal world since both sprites have a script that resets their position if touching the other, both would simultaneously have their positions reset.  However with Scratch, only one of the sprites' positions is changed when this happens. 

This is because the separate threads are not actually running concurrently so the one thread evaluates TRUE for "is touching" and executes its "go to [a far away position]" before the other thread is allowed to evaluate its own "is touching" and when the second gets to it, the first sprite has already moved to a location that is NOT touching which will therefore make the condition evaluate as FALSE. 

I made a quick demonstration for this and uploaded it to http://scratch.mit.edu/projects/andrew_webster/1922193

This is mostly an explanation for what I have observed, but has this been explored by others and is there an elegant solution to this problem? 

Andrew

Offline

 

#2 2011-07-14 17:08:14

roosterman3
Scratcher
Registered: 2010-05-15
Posts: 23

Re: race conditions

yes there is. 
sprite1:

Code:

  [when green flag clicked] [go to X(10) Y(0)] [broadcast resetposition]  [forever [move 10 steps] [wait {pickrandom (0.1) to (0.5) secs}]]

Code:

when i recieve resetposition go to X(10) Y(0)

Code:

 [when green flag clicked] [forever [wait until touching <sprite2>] [broadcast resetposition] ]

Sprite2:

Code:

 [when i recieve resetposition] [go to X(10) Y(0)] [forever [move 10 steps] [wait {pick random (0.1) to (0.5)} secs]

hope that helps.

Last edited by roosterman3 (2011-07-14 17:11:53)


NOTICE: I AM NOT GOING TO BE ON SCRATCH ANYMORE BECAUSE OF MY INTERNET BEING CANCELED.
http://i.imgur.com/YM1nK.png

Offline

 

#3 2011-07-14 18:06:10

sparks
Community Moderator
Registered: 2008-11-05
Posts: 1000+

Re: race conditions

as roosterman said above, use the "broadcast" and "when I recieve" blocks so that when they touch they broadcast "reset". The broadcast will be received by them both and they can then have a script that resets their positions  smile

For future reference, this sort of question belongs in the "all about scratch" section of the fora!  smile


http://img541.imageshack.us/img541/7563/scratchbetabanner.png

Offline

 

Board footer