How do you modify a variable in another process?
DON'T.
Yes, it is possible.
No, it's an amazingly bad idea in any programming language.

First, let us see a simple, obvious, and portable way to do
what you want.  (It has one minor problem which I'll get to.)

shared := Array new: 1.
shared at: 1 put: initialValue.
[ 1 to: 100 do: [:i |
    Transcript show: (shared at: 1); cr
] fork.

The 'shared' object is a secret shared between the new Process and the
(method in the) Process that created it.  Nothing else can see it, let
alone change it.  This is a good thing.

The minor problem I mentioned?
It might not work.  If the two Processes are running on different
cores, and if the compiler is (too) smart (enough), memory writes
from one Process might not be noticed by memory reads at the other.

You should think about processes the way you think about objects.
"How do I change a variable in another object?  DON'T!"
"How do I change a variable in another process? DON'T!"
What variables another object has or another process has are
PRIVATE IMPLEMENTATION DETAILS.
The Object-Oriented rule is

  ASK, DON'T TELL.

That is, you should never *force* an object or process to do
anything, you should ASK it to do something by sending a
message.

The way you send a message to a Process is via a SharedQueue.

shared := SharedQueue new.
[ |text next|
  text := 'Kalimera Kosmou'.
  1 to: 100 do: [:i |
    next := shared nextOrNil.
    next ifNotNil: [text := next].
    Transcript show: text; cr]
] fork.
shared nextPut: 'Pozdrav svijete'.
shared nextPut: 'Hello world'.

With this approach, the receiving process has complete
and absolute control over when the variable ('text') is
changed and indeed whether it is changed.

There are several other tools you can use, but my experience
has been that getting things right using Processes and
SharedQueues FIRST before trying other kinds of things
(like rolling your own Mailbox or Rendezvous classes) makes
concurrent programming so much easier.

It also drives home that the originating process does not
know when or whether the receiving process has acted on
the message, but that's the case with shared variables too,
modern hardware and operating systems being what they are.
It's just more OBVIOUS this way and more CONTROLLED.


On Tue, 2 Mar 2021 at 22:42, <mspg...@gmail.com> wrote:

> Hello everybody, I am kind of new to Pharo so I apologise if my
> question is silly :)
> how can a change a variable in a process while the process is running?
> for example in:
> [[ | msg| msg := 'help me'. 100 timesRepeat: [(Delay forSeconds: 0.5)
> wait. Transcript show: msg; cr]] fork.
>
> how do I change the value of msg while the process is running in order
> to modify what the Transcript is showing?
> is that possible?
> thanks.
> Domenico
>

Reply via email to