Point me to the docs for threads

Ned Konz ned at squeakland.org
Sun Nov 28 19:09:14 UTC 2004


On Saturday 27 November 2004 3:33 pm, Ryan Zerby wrote:
> For my game, I'd like the AI to run in the background for X number of
> seconds. I don't want it to lock up the UI while it's thinking.  In
> other languages, I've done this by firing off the AI
> as a thread, then creating another clock that sent a "stop" message to
> the AI after X seconds.
>
> I see implementing the clock as a Delay class.. but need a bit help
> figuring out the details of forking off the original AI process.
>
> Can someone point me to docs or examples?

Threads (Process in Squeak) are created using the 

 p := [ stuff ] forkAt: priority

idiom.

 p := [ stuff ] fork

is a special case that uses the current process priority.


Priorities are defined in ProcessorScheduler; there is a global one of these 
schedulers called Processor .

So if you want to do stuff in the background you can just go:

 myBackgroundProcess := [ stuff ] forkAt: Processor userBackgroundPriority.

Later you can suspend and/or terminate the process forcibly (a bit rude):

 myBackgroundProcess suspend.
 "later..."
 myBackgroundProcess resume.

 myBackgroundProcess terminate. "done with the process!"

or you can set up one or more SharedQueue instances (better) to communicate 
with it.

 queue := SharedQueue new.
 myBackgroundProcess := [
  | done  message |
  done := false.
  [ done ] whileFalse: [
   message := queue next.
   "... process message ..."
   "message processing could set done"
  ]] forkAt: Processor userBackgroundPriority.


You can also signal an exception in another Process; this might be useful for 
your case (see below).

 myBackgroundProcess := [
  | done  message |
  done := false.
  [ done ] whileFalse: [
 [ message := queue next.
   "... process message ..."
   "message processing could set done" ] on: TimedOutdo: [ :ex | done := true.
 "stuff to do when my life is over"  ]] forkAt: Processor 
userBackgroundPriority.

 "later..."
 myBackgroundProcess signal: TimedOut

We also have Monitor and Semaphore objects to handle shared access to 
resources. Monitors are probably better (higher level) things to use.

A read on an empty queue will block a process (that is, suspend it until 
something is available to read). You can do a wait-with-timeout on a 
Semaphore or Monitor.

You can also (now) do

 [ stuff ] valueWithin: 2000 "msec" onTimeout: [ more stuff ]

which signals a TimedOut exception in the action block, so you can also use 
the pattern:

 [ [ stuff ] on: TimedOut do: [ :ex |  ] ] valueWIthin: 2000 onTimeout: [ ].

-- 
Ned Konz
http://bike-nomad.com/squeak/



More information about the Squeak-dev mailing list