Search code examples
smalltalksqueak

how to use Multi threading in squeak smalltalk?


i would like to know how to work with Threads in squeak smalltlak

b1 := Ball new.
b2 := Ball new.

this 2 next objects should run in different Threads together(Multi threading). how can i do it ?

"Thread 1"
    b1  start:210 at:210.    "start is the name of the method"

"Thread 2"        
    b2  start:310 at:210.

Solution

  • First of all, the Squeak VM only offers green threads, i.e. the VM runs in a single process and threads are simulated inside this single process.

    To use threads (simply called processes in Squeak) you usually send the message #fork or #forkAt: to a block:

    [ b1 start: 210 at: 210 ] fork.
    [ b1 start: 210 at: 210 ] forkAt: Processor userBackgroundPriority.
    

    That's all there is to it really, unless you need facilities for inter process communication. Then you can use a Mutex for critical sections (only one process can be in this section at a time) or a Semaphore for controlling access to a shared resource:

    "before critical section"
    self mutex critical: [ "critical section" ].
    "after critical section"
    
    "access shared resource"
    self semaphore wait.
    "do stuff..."
    "release shared resource"
    self semaphore signal.
    

    The methods #semaphore and #mutex are simply accessors to variables. These variables should not be initialised lazily but before multiple processes may call the methods. That usually means you'll initialise them in the #initialize method:

    initialize
      semaphore := Semaphore new.
      mutex := Mutex new.
    

    The reason for this is that you can not guarantee that a process will not be suspended in the #ifNil: block. This could result in two processes using two different mutexes / semaphores.

    If you need more information, you should take a look at the Deep into Pharo book and maybe read the original Smalltalk books by Adele Goldberg (available at your favourite online book store).