https://www.reddit.com/r/rust/comments/1jwp8jo/do_most_people_agree_that_the_multithreaded/
Rust related

https://www.reddit.com/r/rust/comments/1f920z8/async_rust_can_be_a_pleasure_to_work_with_without/
Rust related

https://bitbashing.io/async-rust.html
Async Rust Is A Bad Language
Sep 8, 2023
After decades of mutex madness, many modern languages heed Hoare’s advice and
provide channels in their standard library.
Rust comes at this problem with an “async/await” model, seen previously in
places like C# and Node.js.6 Here, functions marked async don’t block, but
immediately return a future or promise that can be awaited to produce the result.
    fn foo() -> i32 { /* returns an int when called */ }
    async fn bar() -> i32 { /* returns a future we can .await to get an int */ }


You can trick systems programmers into leveraging GC by calling it “deferred destruction”.
https://www.kernel.org/doc/html/next/RCU/whatisRCU.html
Related to the Linux kernel.
What is RCU? -- “Read, Copy, Update”
The basic idea behind RCU is to split updates into “removal” and “reclamation” phases.
The removal phase removes references to data items within a data structure
(possibly by replacing them with references to new versions of these data items),
and can run concurrently with readers.
The reclamation phase does the work of reclaiming (e.g., freeing) the data items
removed from the data structure during the removal phase.
Splitting the update into removal and reclamation phases permits the updater to
perform the removal phase immediately, and to defer the reclamation phase until
all readers active during the removal phase have completed, either by blocking
until they finish or by registering a callback that is invoked after they finish.


https://bitbashing.io/gc-for-systems-programmers.html
Garbage Collection for Systems Programmers
https://github.com/facebook/folly/blob/main/folly/synchronization/Rcu.h


https://marabos.nl/atomics/
Rust Atomics and Locks
Low-Level Concurrency in Practice
Code examples
https://github.com/m-ou-se/rust-atomics-and-locks


https://assets.bitbashing.io/papers/concurrency-primer.pdf
What every systems programmer should know about concurrency
Matt Kline April 28, 2020


https://without.boats/blog/futures-and-segmented-stacks/
Futures and Segmented Stacks
June 8, 2020


https://blog.cloudflare.com/how-stacks-are-handled-in-go/
How Stacks are Handled in Go
2014-09-15
Segmented stacks give us stacks that grow and shrink on demand.
This was how Go handled stack growing up until recently, but this approach had a flaw.
Shrinking the stack is a relatively expensive operation. It was most felt when
you had a stack split inside a loop.
This was known as the hot split problem. It was the main reason that the Go developers
switched over to a new method of managing stacks, called stack copying.

================================================================================

https://tenthousandmeters.com/blog/python-behind-the-scenes-12-how-asyncawait-works-in-python/


================================================================================

Python is 32 years old language, yet it still doesn't have proper, true parallelism/concurrency.
This is going to change soon, thanks to introduction of a "Per-Interpreter GIL"
(Global Interpreter Lock) which will land in Python 3.12.


https://peps.python.org/pep-0684/
PEP 684 – A Per-Interpreter GIL


===============================================================================

https://tenthousandmeters.com/blog/python-behind-the-scenes-13-the-gil-and-its-effects-on-python-multithreading/
Python behind the scenes #13: the GIL and its effects on Python multithreading
---
Experience report: Larry Hastings' Gilectomy project started in 2016.
---
there is an initiative to introduce multiple GILs to CPython. It's called subinterpreters.
The idea is to have multiple interpreters within the same process.
Threads within one interpreter still share the GIL, but multiple interpreters can run parallel.
No GIL is needed to synchronize interpreters because they have no common global state
and do not share Python objects. All global state is made per-interpreter,
and interpreters communicate via message passing only. The ultimate goal is to
introduce to Python a concurrency model based on communicating sequential
processes found in languages like Go and Clojure.

===============================================================================

https://github.com/llvm/llvm-project/blob/main/llvm/docs/Atomics.rst
LLVM Atomic Instructions and Concurrency Guide


===================================================================================
Extracted from
https://news.ycombinator.com/item?id=21227430
Larry Wall has approved renaming Perl 6 to Raku (github.com)


weff_
I'm trying to understand, what kind of scripting requires first-class concurrency that isn't fulfilled by say Python?


dragonwriter
For concurrency I think Raku has slightly more developed async support than Python, but the bigger advantage, I think,
is in parallelism where, aside from the CPython GIL limiting practical parallelism in the main implementation
(which is a big deal), Python as a language lacks the parallel iterables produced by the hyper (parallel but constrained
to return in order) and race (parallel and not constrained in order) methods on the Iterable role in Raku, or anything
like Raku’s hyperoperators that are semantically concurrent and parallelizable at the discretion of the optimizer.
(Come to think of it, while also parallel, all those are also high-level concurrency constructs that Python lacks
equivalents to.)
Python as a language can support parallelism via threads, and CPython as an implementation can via multiprocessing,
but those are both very low level abstractions; Raku has higher level abstractions which allow much more succinct
expression of parallel operations.


Too
Sounds like multiprocessing.Pool.imap and imap_unordered?
When dealing with io you also have async/await equivalent iterators like asyncio.as_completed().


Grinnz
I am not that familiar with Python, but the GIL has long prevented any real in-process concurrency.
Perl has concurrency but it's complex, heavy, and poorly supported.
Raku's approach to this is built to avoid all these problems (like Elixir).


weff_
I agree the GIL is a problem but it's only an issue for CPU-bound problems.
Is there really an important amount of CPU-bound work that is written in a scripting language?
If it's CPU-bound, wouldn't you want to use something lower level?


nuclear_eclipse
If it's entirely CPU bound, you can use multiprocessing to negate most of the GIL issues,
and transparently send inputs/outputs between the parent and child processes.
If it's I/O bound, then AsyncIO is a great way to express asynchronous workflows.
If it's a combination of both I/O and CPU bound workloads, there are ways to mix multiprocessing
and AsyncIO to better saturate your cores without losing the simplicity or readability of Python:
https://github.com/jreese/aiomultiprocess


weff_
Very true, I had not even thought about the multiprocessing package;
it's sometimes not as convenient as multithreading but it'll get those other cores working.


karmakaze
It's not just CPU bound problems, handling multiple overlapping i/o operations is more trouble than it ought to be.


weff_
Can you expand a bit on that? I'm not familiar with the issue you're describing.


Grinnz
Indeed and as a Perl developer I make use of XS/external libraries, cooperative multitasking
(event loops/promises), and forking to cover these use cases.
It doesn't preclude wanting the additional option to take advantage of threads in a useful way, since they do exist.


vaer-k
Why should first-class concurrency needs be required to script in Elixir?
This question seems to imply that Python is somehow a default language and special requirements must be needed to
justify writing in something else. Elixir is general-use and pleasant to write scripts in so seems reasonable to me
for someone to do so if that's their thing.


weff_
Ovid2 said Perl6 has a good concurrency model
lliamander replied that Elixir does too and it's worth a look
To that, 7thaccount replied that Perl6 and Elixir fill different niches.
So far, it seems Perl6 fills a niche that requires scripting and first-class concurrency.
My question then is: what is this niche that requires very solid concurrency but also scripting.
In other words, what does Perl6 have in terms of concurrency that Python does not (given they are both scripting languages)?


Ultimatt
Jonathan Worthington (Rakudo Compiler Architect). Keynote: Perl 6 Concurrency
https://www.youtube.com/watch?v=hGyzsviI48M


lliamander
A fair question.
I don't know of many instances where scripting and concurrency would be needed in the same application.
But if you wanted to use single language both for scripting tasks and applications that require concurrency,
then Raku or Elixir would work.
One instance I can actually think of, that would be specific to Erlang/Elixir, is if you have a long running
service that you sometimes run batch jobs against (like importing data from a CSV). An Elixir script can hook
directly into an Elixir/Erlang service and interact with it using message passing. It's a heck of a lot simpler
than RMI, and avoids the need to expose new HTTP endpoints specifically for such tasks.


weff_
Is that like the relationship between C# and PowerShell?


lliamander
I think so, at least in some ways.
I've shipped a project using PowerShell to script Windows Server/Hyper-V, and it was a pretty pleasant experience.
Having a scripting language that not only does typical scripting stuff (wrangling text, etc.) and understands
your application's objects is excellent.
Some differences:
* You can actually write your whole application in Elixir, whereas I could not see doing that with PowerShell
* In Erlang/Elixir, instead of objects you have processes. Think of your application as a microservice architecture
  on steroids, using the Erlang RPC protocol as a means for inter-process communication.
Because each process just sends and receives messages, your script can just send messages to any of the processes
that make up your application, as if they were your own service. All you have to do is connect to the remote
application using the Erlang Distribution Protocol (to connect different runtimes over the network).


weff_
I heard so much about the actor model, I should really try it in its intended glory one day.


lliamander
It's a trip, and it took me a little while to wrap my head around.
However, I now much prefer it to working with other concurrency abstractions (such as callbacks).


labster
Does Python 3 have any operators that transform ordinary method calls into concurrent method calls?
Perl 6/Raku does.


dragonwriter
More to the point, does Python 3 have operators that transform sequential operations into operations
that are both concurrent and parallelizable, and, in the case of iteration, provide control of parallelism
parameters and whether results are constrained to be in-order or not.
To which the answer is “not only does Python not have them, but with the GIL CPython couldn't do much with
them even if the language had them.”


maksimum
Yes, async/await. https://docs.python.org/3/library/asyncio-task.html#awaitabl...
Coroutines and Tasks


weff_
Is that a bit like Go's `go` keyword?
edit: that is, as far as I can tell, after a quick Google, it's not too different from Python's Thread object.


pmezard
It is, python Threads are system threads.


greggman2
I'm embarrased to say I write scripts in node :P
I used to write scripts in python but I've been writing so much JS that it's just easier for me in node.
Plus, node defaults to locally installed deps so I don't have to deal with virutal environments.


tekknik
Why do you think this is embarrassing? Javascript is great for small scripts. Largr codebases then sure


Grinnz
Which is a similar response to the comments asking "why Perl over Python?" I ask, why not (both)?


dnautics
Well just from experience untangling async calls in python is a nightmare and sometimes hard to reason about.
The red/blue function problem is real. Meanwhile dispatching concurrent long-running scripting tasks is basically
trivial in elixir (Enum.map over Task.async, then Enum.map over Task.await)


ajoseps
I'm guessing because Python's concurrency relies on the Global Interpreter Lock.
Although I think concurrent.futures might address that. Haven't worked with python concurrency libraries in a bit.


weff_
as I posted above:
I agree the GIL is a problem but it's only an issue for CPU-bound problems.
Is there really an important amount of CPU-bound work that is written in a scripting language?
If it's CPU-bound, wouldn't you want to use something lower level?


zaphirplane
There is machine learning, which usually calls into numpy or other c extensions With a lot of the data preparation
done in python


rubyn00bie
tldr; Using a scripting language that allows for native threads or has a strong concurrency model builtin to the core
would be beneficial for any CPU bound scripting task...
Python's concurrency model is good for waiting on network or disk I/O because of its GIL (Global Interpreter Lock):
https://realpython.com/python-gil/#the-impact-on-multi-threa...
If your program is CPU bound the GIL will slow you down.
I'm sure since the python ecosystem is quite vast there are ways around the GIL...
but then you have to worry about every library you use not supporting "real" multi-threading,
or (b)locking for no reason and shitting all over your efforts.


weff_
As I've posted above, I'm a bit confused by CPU-bound work being processed in a scripting language.
If you're planning on doing intense CPU-bound work, maybe use a lower-level language?
I'm not saying abandon Python: you can extend Python with C or just use IPC to transfer data between
a Python front-end and a computation back-end.


zmmmmm
At one time it was an obvious dichotomy that you would not use a scripting language for CPU bound work,
but these days it is a much more blurry line. Partly because modern efficient languages are becoming ergonomic
enough to work well as scripting languages while still giving you very good performance.
I actually love doing CPU bound work in Groovy which is usually described as a scripting language.
But it gets converted straight to java byte code which is JIT'd and ends up as machine code.
It only takes a few static typed hints here and there and it runs in the same league as C++ implementations.
And it gets Java's excellent concurrency support for free.


rubyn00bie
I totally you feel you, I guess I thought your question was substantially more surface level than it was. My apologies.
I'm personally with you. I also don't tend to think object boxing is really the performance bottleneck for most applications,
and if/when it is, likely the other requirements should've already ruled out using one (a scripting language).
It's like writing Nifs for Elixir, yeah sure you _can_, they have their purpose, but you could also just write another
application to do that one thing and like you said, use IPC.
So in summary, we agree with each other, here's to:
the right tool for the job!


===================================================================================
node.js

http://bjouhier.wordpress.com/2012/03/11/fibers-and-threads-in-node-js-what-for/
node-fibder : https://github.com/laverdet/node-fibers
Threads  à gogo : https://github.com/xk/node-threads-a-gogo


===================================================================================
Lock-free programmming

http://mintomic.github.io/
Mintomic
A Small, Portable Lock-Free API

http://preshing.com/20130618/atomic-vs-non-atomic-operations/

https://github.com/ivmai/libatomic_ops/

===================================================================================

https://news.ycombinator.com/item?id=6560214
No More Callbacks: 10,000 Actors, 10,000 Threads, 10,000 Spaceships

https://github.com/Amanieu/asyncplusplus

http://www.mail-archive.com/rebol-list@rebol.com/msg09673.html
[REBOL] Re: About CONTINUATIONS

http://stackoverflow.com/questions/2708033/technically-why-is-processes-in-erlang-more-efficient-than-os-threads

http://www.sics.se/~joe/ericsson/du98024.html
Performance Measurements of Threads in Java and Processes in Erlang

https://groups.google.com/forum/?hl=en-GB&fromgroups=#!topic/qilang/UVG_aqH1n5U

http://www.haskell.org/haskellwiki/GHC/Data_Parallel_Haskell


http://herbsutter.com/welcome-to-the-jungle/


http://threadingbuildingblocks.org/

http://docs.python.org/2/c-api/init.html
Python/C API Reference Manual
Initialization, Finalization, and Threads

http://docs.python.org/2/library/multiprocessing.html
16.6. multiprocessing — Process-based “threading” interface

http://www.voidspace.org.uk/python/weblog/arch_d7_2008_11_01.shtml#e1028

http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-computing/


=====================================================================
RexxActivation.hpp
getReserveCount
getVariableDictionary

Modification des accesseurs qui renvoient le dictionnaire et le compteur
Le but est d'avoir l'info, même si l'activation n'a pas encore été mise à jour avec ces infos.
D'après ce que je comprends, la mise à jour se fait uniquement s'il y a accès à une variable.


            this->settings.object_variables = this->receiver->getObjectVariables(this->scope);
Le receiver est tout objet :
   RexxObject          *receiver;      /* target of a message invocation    */
ObjectClass.hpp
     RexxVariableDictionary *getObjectVariables(RexxObject *);


=====================================================================


Le flag object_scope == SCOPE_RESERVED est local à chaque activation.
J'ai l'impression que c'est une optimisation et il n'apporte pas une info très utile...
Ce qui est plus utile, c'est si le dictionnaire de variable est reservé :
this->settings.object_variables->reserve(this->activity);
et par qui :
this->reservingActivity

guard on
guard off

        ==========================================
        JLF : ici le context est un RexxACtivation
        ==========================================
        if (!(instructionFlags&guard_on_form))      /* is this the OFF form?             */
        {
            context->guardOff();             /* set unguarded status in activation*/
        }
        else
        {
            context->guardOn();              /* set guarded status in activation  */
        }



guard on when expression
RexxInstructionGuard::execute(
    RexxActivation      *context,      /* current activation context        */
    RexxExpressionStack *stack )       /* evaluation stack                  */

        size = variableCount;              /* get variable list count           */
        for (i = 0; i < size; i++)       /* loop through the variable list    */
        {
            /* set a guard on each variable,     */
            /* counting the guards on each       */
            /* variable that is actually exposed */
            this->variables[i]->setGuard(context);
        }

        if (!(instructionFlags&guard_on_form)) /* is this the OFF form?             */
        {
            context->guardOff();             /* set unguarded status in activation*/
        }
        else
        {
            ==============================================================================
            JLF : DONC ON RESERVE LE DICTIONNAIRE AVANT MËME DE TESTER L'EXPRESSION ??????
            ==============================================================================
            context->guardOn();              /* set guarded status in activation  */
        }


        ================================================
        JLF : il y a UN SEUL currentActivity dans le système (!!!!)
        C'est une variable statique de ActivityManager
        ================================================
        ActivityManager::currentActivity->guardSet();       /* initialize the guard sem          */         JLF : c'est un RESET !


        /* get the expression value          */
        result = this->expression->evaluate(context, stack);
        context->traceResult(result);      /* trace if necessary                */
                                           /* do first evaluation without       */
                                           /* establishing any variable guards  */
                                           /* false on first attempt?           */
        if (!result->truthValue(Error_Logical_value_guard))
        {
            do                             /* need to loop until true           */
            {
                stack->clear();                /* clear the expression stack        */
                context->guardWait();       /* establish guards and wait         */                         JLF : RexxActivation::guardWait
                ActivityManager::currentActivity->guardSet();   /* initialize the guard sem          */     JLF : c'est un RESET !
                result = this->expression->evaluate(context, stack);
                context->traceResult(result);  /* trace if necessary                */
                                               /* while this is still false         */
            } while (!result->truthValue(Error_Logical_value_guard));
        }
        for (i = 0; i < size; i++)       /* loop through the variable list    */
        {
            /* set a guard on each variable,     */
            /* counting the guards on each       */
            /* variable that is actually exposed */
            this->variables[i]->clearGuard(context);
        }




Il y a un sémaphore par instance de RexxActivity pour les guard expressions
   SysSemaphore        guardsem;       /* guard expression semaphore        */




void RexxActivation::guardWait()
/******************************************************************************/
/* Function:  Wait for a variable in a guard expression to get updated.       */
/******************************************************************************/
{
    int initial_state = this->object_scope;  /* save the initial state            */
                                         /* have the scope reserved?          */
    if (this->object_scope == SCOPE_RESERVED)
    {
        /* tell the receiver to release this */
        this->settings.object_variables->release(this->activity);
        /* and change our local state        */
        this->object_scope = SCOPE_RELEASED;    /* do an assignment! */
    }
    this->activity->guardWait();         /* wait on a variable inform event   */
                                         /* did we release the scope?         */
    if (initial_state == SCOPE_RESERVED)
    {
        /* tell the receiver to reserve this */
        this->settings.object_variables->reserve(this->activity);
        /* and change our local state        */
        this->object_scope = SCOPE_RESERVED;    /* do an assignment! */
    }
}



void RexxActivity::guardSet()
/******************************************************************************/
/* Function:  Clear a guard expression semaphore in preparation to perform a  */
/*            guard wait                                                      */
/******************************************************************************/
{
    guardsem.reset();               /* set up for guard call             */
}






===============================================================================

Relation entre RexxActivity et thread

class RexxActivity
   thread_id_t threadIdMethod();
   bool isThread(thread_id_t id) { return currentThread.equals(id); }

   SysActivity currentThread;            /* descriptor for this thread        */


===============================================================================

RexxActivity.cpp
RexxActivity::RexxActivity(bool createThread)
: runsem("RexxActivity::runsem"), guardsem("RexxActivity::guardsem")

Le nom des variables passé en paramètre est bien stocké
mais ensuite effacé par
this->clearObject();

défini dans ObjectClass.hpp
  class RexxInternalObject : public RexxVirtualBase{
     inline void   clearObject() { memset(getObjectDataSpace(), '\0', getObjectDataSize()); }

     static inline size_t getObjectHeaderSize() { return sizeof(RexxInternalObject); }
     inline size_t getObjectDataSize() { return getObjectSize() - getObjectHeaderSize(); }
     inline void  *getObjectDataSpace() { return ((char *)this) + getObjectHeaderSize(); }


====================================================================================
https://mail.google.com/mail/?shva=1#inbox/12eb5d34607ac1c0
Guard conditions nest.  So the guard off in the m1 method does not
completely remove the locking from that thread.  It only removes the
guarded condition caused by entry to that method, so the object is
still locked by that thread.


RexxActivation.object_scope est une optimisation :
si == SCOPE_RELEASED alors pas besoin d'aller voir le dictionnaire de variables this->settings.object_variables
sinon, le reserveCount est testé


RexxActivation.hpp
   inline void       guardOff()
    {
                                           /* currently locked?                 */
      if (this->object_scope == SCOPE_RESERVED) {
                                           /* release the variable dictionary   */
        this->settings.object_variables->release(this->activity);
                                           /* set the state to released         */
        this->object_scope = SCOPE_RELEASED;
      }
    }


RexxActivation.cpp
void RexxActivation::guardOn()
{
    ====================================
    JLF : si object_scope indique que le dictionnaire est déjà reservé, rien à faire.
    sinon, on demande à reserver le dictionnaire mais ça peut être bloquant. En sortie, on est SCOPE_RESERVED.
    ====================================
    /* currently in unguarded state?     */
    if (this->object_scope == SCOPE_RELEASED)
    {
        /* not retrieved yet?                */
        if (this->settings.object_variables == OREF_NULL)
        {
            /* get the object variables          */
            this->settings.object_variables = this->receiver->getObjectVariables(this->scope);
        }
        /* lock the variable dictionary      */
        this->settings.object_variables->reserve(this->activity);			JLF : peut BLOQUER si besoin (object_variables est un RexxVariableDictionary)
        /* set the state here also           */
        this->object_scope = SCOPE_RESERVED;						JLF : donc cette activation n'aura le status SCOPE_RESERVED que lorsque la réservation est effective, après attente si besoin
    }
}


====================================================================================

interpreter/execution/RexxVariableDictionary.cpp
RexxVariableDictionary::release
this->reserveCount


RexxVariableDictionary::reserve
if (this->reservingActivity == OREF_NULL) // currently unlocked ?
this->reserveCount++;


RexxVariableDictionary::release
this->reserveCount--;


RexxVariableDictionary::transfer



Plus de détails
---------------
Un dictionnaire est associé à une activité qui l'a réservé.
3 cas :
- dictionnaire pas encore réservé : assignation du reservingActivity et reserveCount=1
- dictionnaire déjà réservé et l'appel se fait pour la même activité : reserveCount++
- dictionnaire déjà réservé et l'appel se fait par une autre activité :
  l'activité appelante est ajoutée en fin de queue, et mise en attente


void RexxVariableDictionary::reserve(
  RexxActivity *activity)              /* reserving activity                */
/******************************************************************************/
/* Function:  Reserve a scope on an object, waiting for completion if this    */
/*            is already reserved by another activity                         */
/******************************************************************************/
{
    /* currently unlocked?               */
    if (this->reservingActivity == OREF_NULL)
    {
        /* set the locker                    */
        OrefSet(this, this->reservingActivity, activity);
        this->reserveCount = 1;            /* we're reserved once               */
    }
    /* doing again on the same stack?    */
    else if (this->reservingActivity == activity)
    {
        this->reserveCount++;              /* bump the nesting count            */
    }
    else
    {                               /* need to wait on this              */
                                    /* go perform dead lock checks       */
        this->reservingActivity->checkDeadLock(activity);
        /* no list here?                     */
        if (this->waitingActivities == OREF_NULL)
        {
            /* get a waiting queue               */
            OrefSet(this, this->waitingActivities, new_list());
        }
        /* add to the wait queue             */
        this->waitingActivities->addLast((RexxObject *)activity);
        /* ok, now we wait                   */
        activity->waitReserve((RexxObject *)this);
    }
}


====================================================================================


RexxActivation::run
/* Function:  Run a REXX method...this is it!  This is the heart of the       */
/*            interpreter that makes the whole thing run!                     */
...
                if (isGuarded())
                {
                    /* get the object variables          */
                    this->settings.object_variables = this->receiver->getObjectVariables(this->scope);
                    /* reserve the variable scope        */
                    this->settings.object_variables->reserve(this->activity);
                    /* and remember for later            */
                    this->object_scope = SCOPE_RESERVED;
                }
...



RexxVariableDictionary * RexxActivation::getObjectVariables()
/******************************************************************************/
/* Function:  Return the associated object variables vdict                    */
/******************************************************************************/
{
    /* no retrieved yet?                 */
    if (this->settings.object_variables == OREF_NULL)
    {
        /* get the object variables          */
        this->settings.object_variables = this->receiver->getObjectVariables(this->scope);
        if (isGuarded())                   /* guarded method?                   */
        {
            /* reserve the variable scope        */
            this->settings.object_variables->reserve(this->activity);
            /* and remember for later            */
            this->object_scope = SCOPE_RESERVED;
        }
    }
    /* return the vdict                  */
    return this->settings.object_variables;
}


================================================================================
code review
================================================================================

I interlace your comments with the C++ source, because only the source code is the truth.
Had no time to reword your description (because I think some parts should be reworded).


> On 7 Jul 2024, at 12:20, Rony G. Flatscher <Rony.Flatscher@wu.ac.at> wrote:

> having slept over it, maybe it is a good idea to reconcile all aspects that can be observed and understood by the comments, and try to come up with the most simple description, that is understandable and complete. This is such an attempt:

    +1
    Not an easy subject, the description must be compared with the source code, again and again.

> ooRexx does not employ a binary guard lock, rather a count based guard lock, with the following rules:
    ok, you explained already that in rexxref:
    "L5": "L" stands for scope lock count and the number (a counter) indicates how many object scope lock reservations have taken place at that point in time. Whenever another guarded method of the same scope gets invoked the object's scope lock count increases by one, upon return the object's scope lock count decreases by one.



> if the guard lock count is > 0 for a specific invocation, then only invocations of guarded methods are possible on that specific invocation (no matter on which thread in the case of REPLY);
    To reword because unguarded methods can access, as written in point 4.
    “specific invocation” sounds incorrect when talking about lock count. Should be “specific scope”

    The scope lock is a property of the invocation (RexxActivation):
        // guard scopy settings
        typedef enum
        {
            SCOPE_RELEASED = 0,
            SCOPE_RESERVED = 1,
        } GuardStatus;
        GuardStatus     objectScope;     // reserve/release state of variables
    “scopy” is not a typo on my part.
    Don’t know if it’s a typo by the programmer, or if it’s intentional.

    The lock count is a property of the scope’s variables (VariableDictionnary):
        unsigned short reserveCount;         // number of times reserved
        RexxClass *scope;                    // scopy of this object dictionary


> an attempt to invoke of a guarded method from any other invocation (would run on a separate thread) gets blocked, waiting on the guard lock count to drop to 0 before attempting to acquire the guard lock,
    ok, same comment as the previous:
    The critical resource is the scope’s variables (technically the VariableDictionnary)

    reserve() is called when the method requesting the access to the scope’s variables is guarded:

    /**
     * Reserve a scope on an object, waiting for completion if this
     * is already reserved by another activity
     *
     * @param activity The activity reserving the scope.
     */
    void VariableDictionary::reserve(Activity *activity)
    {
        // not reserved at all?  This is easy.
        if (reservingActivity == OREF_NULL)
        {
            // Activity objects are automatically safe from
            // garbage collection and this is something we
            // want to occur as quickly a possible, so just assign
            // this value directly without worrying about old-to-new issues.
            reservingActivity = activity;
            reserveCount = 1;
        }
        // doing this again on the same stack?  Just bump the
        // nesting count. Note that nested activities created via
        // attach thread will count as being part of the same activity
        // stack since they are on the same system thread.
        else if (activity->isSameActivityStack(reservingActivity))
        {
            reserveCount++;
        }
        // we have an access collision.  We need to wait on this one.
        else
        {
            reservingActivity->checkDeadLock(activity);
            // this one we need to use setField()
            if (waitingActivities == OREF_NULL)
            {
                setField(waitingActivities, new_array());
            }
            // add to the end of the queue
            waitingActivities->append(activity);
            // ok, now we wait
            activity->waitReserve(this);
        }
    }

    release() is called when the guarded method is ended, or when it executes guard off:

    /**
     * Release the lock on an object's variable dictionary.
     *
     * @param activity The activity owning the lock.
     */
    void VariableDictionary::release(Activity *activity)
    {
        reserveCount--;
        // if this is the last reserver on this activity, we just clear everything out
        if (reserveCount == 0)
        {
            // setField() not required here.  See comment in reserve()
            reservingActivity = OREF_NULL;
            // potential waiters?
            if (waitingActivities != OREF_NULL && !waitingActivities->isEmpty())
            {
                // remove the first item and make it the new reserver
                reservingActivity = (Activity *)waitingActivities->removeFirst();
                reserveCount = 1;
                // wake up the waiting activity.
                reservingActivity->guardPost();
            }
        }
    }


> if a REPLY keyword statement is processed in a currently guarded method the remainder of the invocation will remain guarded such that no other guarded methods can be invoked from different invocations (on different threads), this keeps serializing access to guarded methods from different invocations as they get blocked,

> if a REPLY keyword statement is processed in a currently unguarded method the remainder of the invocation will continue on a different thread also unguarded; in this case if the guard lock count is 0 a guarded method could get invoked in between of the switch to the new thread,
    ok

    transfer is called by RexxActivation::run when objectScope == SCOPE_RESERVED (i.e. when the invocation holds the scope lock).
    Here, the reserveCount is >= 1.


    /**
     * Transfer the variable dictionary lock to another
     * activity.  Occurs when a reply has been issued.
     *
     * @param activity The new activity.
     *
     * @return true if the reservation could transfer, false if there
     *         is nesting taking place that prevents this from occurring.
     */
    bool VariableDictionary::transfer(Activity *activity)
    {
        // if there is only a single level of nesting, just change the reserving activity
        if (reserveCount == 1)
        {
            // NOTE:  Not using setField
            reservingActivity = activity;
            // indicate the transfer is complete
            return true;
        }
        // multiple nesting levels...we perform a release for this activation level,
        // but this activity still owns the lock.
        else
        {
            release(activity);
            // could not release.
            return false;
        }
    }

    In RexxActivation::run when in REPLIED state:
                    // if we have the scope lock, try to transfer it to the new activity.  If
                    // the lock is nested on this activity, then we will need to
                    // obtain it when we start running on the new thread.
                    if (objectScope == SCOPE_RESERVED)
                    {
                        if (!settings.objectVariables->transfer(activity))
                        {
                            // this will tell us that we need to try grabbing this again.
                            settings.setTransferFailed(true);
                        }
                    }

    In RexxActivation, the part after the reply, in the new thread:
        // resuming on a new thread after a reply
        else
        {
            // if we could not keep the guard lock when we were spun off, then
            // we need to reacquire (and potentially wait) for the lock now.
            if (settings.hasTransferFailed())
            {
                settings.objectVariables->reserve(activity);
                // turn off the failure flag in case we spin off again.
                settings.setTransferFailed(false);
            }
        }



> unguarded methods can always be invoked from any thread independent of guarded methods.
    ok

    In RexxActivation::run, we can see that reserve is called only when the method is guarded
    so an unguarded method is not blocked:
                // this is a method call.  We need to do some method setup.
                else
                {
                    // guarded methods need to reserve the object scope
                    if (isGuarded())
                    {
                        // get the object variables and reserve these
                        settings.objectVariables = receiver->getObjectVariables(scope);

                        // For proper diagnostic in case of deadlock, do the trace now
                        traceEntry();

                        settings.objectVariables->reserve(activity);
                        objectScope = SCOPE_RESERVED;
                    }
                    // initialize the SELF and SUPER variables
                    setLocalVariable(GlobalNames::SELF, VARIABLE_SELF, receiver);
                    setLocalVariable(GlobalNames::SUPER, VARIABLE_SUPER, receiver->superScope(scope));
                }

    We can see in the code above that settings.objectVariables is assigned only when the method is guarded.
    But there is also this method which takes care of settings.objectVariables.

    /**
     * Return the object variables dictionary for the current
     * scope level.
     *
     * @return the target object variables.
     */
    VariableDictionary* RexxActivation::getObjectVariables()
    {
        // not retrieved yet?  We need the dictionary from the current method scope.
        if (settings.objectVariables == OREF_NULL)
        {
            settings.objectVariables = receiver->getObjectVariables(scope);
            // are we a guarded method?  Get the guard lock now.
            if (isGuarded())
            {
                settings.objectVariables->reserve(activity);
                objectScope = SCOPE_RESERVED;
            }
        }
        return settings.objectVariables;
    }


> This would imply that in your deadlock example that the invocation of M2 in the routine's invocation blocks until the lock count drops to 0 in the M1 invocation as that invocation has a guard lock count > 0.

    yes but the lock count is a property of the scope’s variables, not a property of an invocation.


Illustration (the full trace is in the mail)

[T2 I3 G   A1 L1 *  ]  10 *-* reply
[T2 I3 G   A1 L1 *  ]     <I< Method "INIT" with scope "CLZ"
[T2 I2]                   >>>   "a CLZ"
[T2 I2]                 2 *-* call syssleep 0.5
[T3 I3 G   A1 L1 *  ]     >I> Method "INIT" with scope “CLZ”            rule 3: still guarded
[T3 I3 G   A1 L1 *  ]  12 *-* self~m1                                   rule 1: invokation on the same thread
[T3 I4 G   A1 L1    ]     >I> Method "M1" with scope “CLZ”              early entry trace, before a possible reservation: the guard lock counter and guard lock are not yet updated
[T3 I4 G   A1 L2 *  ]  15 *-* expose a   -- exclusive access            attribute pool reserved from the same thread, not blocking, counter + 1 = 2 (It’s not the expose instruction which changes the counter)
The guard off in M1 will release the attribute pool, but the counter will still be 1.
The invokation o~m2 from another thread will be blocked: dead-lock.


[T2 I3 G   A1 L1 *  ]  10 *-* reply
[T2 I3 G   A1 L1 *  ]     <I< Method "INIT" with scope "CLZ"
[T2 I2]                   >>>   "a CLZ"
[T2 I2]                 2 *-* call syssleep 0.5
[T3 I3 G   A1 L1 *  ]     >I> Method "INIT" with scope “CLZ”            rule 3: still guarded
[T3 I3 G   A1 L1 *  ]  11 *-* guard off  -- now no deadlock anymore     release the attribute pool. The trace is done before the effective release
[T3 I3 G u A1 L0    ]  12 *-* self~m1    -- now unguarded               attribute pool released: counter - 1 = 0
[T3 I4 G   A1 L0    ]     >I> Method "M1" with scope "CLZ"
[T3 I4 G   A1 L1 *  ]  15 *-* expose a   -- exclusive access            attribute pool reserved from the same thread, not blocking, counter + 1 = 1
The guard off in M1 will release the attribute pool, and the counter will become 0.
The invokation o~m2 from another thread will not be blocked: no dead-lock.
