0

I've been messing around with a custom boot loader for my Raspberry Pi 3B. I've found that, if I use a static variable in a function, all cores share the same value for that static variable.

Here's the code I'm running on each core. It's based on something found online:

void kernel_main(unsigned int processor_index)
{

  static unsigned int current_processor_index = 0;

  if (processor_index == 0) {
    uart_init();
  }

  while (processor_index != current_processor_index);

  uart_send_string("Hi from processor ");
  uart_send(processor_index + '0');
  uart_send_string("!\r\n");

  current_processor_index++;
  
  if (processor_index == 0) {
    // if current_processor_index == 4 then all processors send message
    while (current_processor_index != 4)
      ;
    for (;;) {
      uart_send(uart_recv());
    }
  }
}

Each core hangs until the static current_processor_index takes the value of the processor_index. Since the RPi3 has 4 cores, the output is:

Hi from processor 0!
Hi from processor 1!
Hi from processor 2!
Hi from processor 3!

Why does this work? I'm struggling to find answers online. Thanks!

pwasoutside
  • 343
  • 1
  • 10
  • Can you first explain why you think they shouldn't share the same value? If two different cores access a hard disk they read the same files, why do you think accessing memory should be different from that? – Tom V Oct 15 '22 at 19:04
  • It's a good point you raise. I guess I'm unsure where the C compiler stores static variables. If it's saved in the .data section, always at the same address, then presumably each core would be looking at the same address. If this address is chosen at run time, then I don't understand how each core could share this static variable – pwasoutside Oct 15 '22 at 20:29
  • 2
    Static variables are usually in data or bss. Even if address randomization is used, if the cores are running within the same address space (typical in the same process) then you would expect them to all get the same address. Only if you have set up different address mapping (eg for a different process) would it be different. Obviously if you are writing your own operating system then this is totally up to you whether you set up the the MMU differently for the different cores. – Tom V Oct 15 '22 at 20:37
  • The magic is that the code is shared between core and you just trigger different core to execute this. Additionally, you need to check whether it is executed by different core or by a single core as well. – ThongDT Oct 16 '22 at 06:21
  • 1
    The behaviour is static variables is a requirement of the language. It would be more surprising, (and wrong) if this were not the case. Some execution environments support _thread-local storage_ (TLS) that provide static-like behaviour at the thread rather than process level. – Clifford Oct 16 '22 at 07:14

0 Answers0