I know of 4 common techniques for working around the parallel usage rules (there may well be more), whilst sharing memory at high level, so thought I'd share them. Feel free to share your examples too!
Warning: sharing memory can damage your health! Make sure you understand exactly what is going on to avoid latent strange and difficult to solve runtime bugs!
Here's the first method, using unsafe pointers (introduced in tools 13). It's a nice way of sharing a global using a(n unsafe) pointer.
Pros: It's fairly familiar C usage, and is fast (no bounds checking)
Cons: (outside of normal shared memory and pointer type risks) Extra syntax to declare unsafe sections, although TBF it makes it pretty explicit to other readers that something (potentially) dodgy could be going on .
Code: Select all
#include <xs1.h>
#include <stdio.h>
#include <timer.h>
unsigned g_global = 0;
void task1(void){
volatile unsigned * unsafe glob_ptr;
unsafe {
glob_ptr = &g_global;
}
unsafe{
printf("Ptr set to %d\n", *glob_ptr);
while(*glob_ptr == 0);
printf("Ptr set to %d\n", *glob_ptr);
}
}
void task2(void){
volatile unsigned * unsafe glob_ptr;
unsafe {
glob_ptr = &g_global;
}
delay_microseconds(1);
unsafe{
*glob_ptr = 1234;
}
}
int main(void){
par{
task1();
task2();
}
return 0;
}