User Tools

Site Tools


mt6502:locals
Translations of this page:


Multithreading on retrocomputers

HOW TO MANAGE LOCAL VARIABLES

Since protothreads do not save stack context, local variables are not preserved when protothread hangs. More correctly, the value of these local variables is undefined.

This code, therefore, will never be able to run or compile correctly:

  MR_PT_THREAD(f) {
      unsigned char x; // <--- valore indefinito
      MR_PTI_BEGIN();
      ...
      MR_PTI_END();
  }

This means that local variables cannot be used. The alternative is therefore to resort either to global variables or to extend the context of the protothread.

The first solution is the simplest, and is indicated when there is only one thread of that type. In this case, the variable must be moved from the local definition to outside the protothread definition:

  unsigned char x;
  
  MR_PT_THREAD(f) {
      MR_PTI_BEGIN();
      ...
      MR_PTI_END();
  }

When there are multiple threads, each of them should have its own specific copy of this local variable. This is possible by extending the mr_protothread type with the MR_PT_CTX annotation. For example:

  MR_PT_CTX(f, unsigned char x);
  
  MR_PT_THREAD_EXT(f,f_protothread) {
      MR_PTI_BEGIN();
      ...
      MR_PTI_END();
  }

Note that we had to use the MR_PT_THREAD_EXT variant to spawn a thread that has an extended context, defined by MR_PT_CTX.

Move to "HELLO WORLD" WITH TWO PROTOTHREADS.