3 ms·
I'm feeling very curious why all of that is necessary, and why it can't be hidden away in a function or a macro? Would anybody mind explaining?
by dale_glass 3y ago
I'm feeling very curious why all of that is necessary, and why it can't be hidden away in a function or a macro? Would anybody mind explaining?
- afiori 3y agoit can be hidden in a function
- leoedin 3y agoIt can be hidden away in a function or a macro. In any sensible code base it would be.
- arlort 3y agoThis example is attempting to give the low level view of how peripherals can be safely shared between multiple threads https://docs.rust-embedded.org/book/concurrency/index.html?highlight=MY_GPIO#sharing-peripherals https://docs.rust-embedded.org/book/concurrency/index.html?h... You would definitely hide it behind a function if you need it, but that's not very useful in a guide that wants to teach you what it looks like without the function
- db48x 3y agoEven better than hiding it away is splitting it in half. The code was written that way so that two tasks running simultaneously could not both try to write to the same pin at the same time. But writing it as a one–liner that you use over and over is the wrong approach, because then you’re unlocking the mutex (and other layers) before every write to the pin, and then locking it back down afterwards. If you then sleep before writing the next bit to that pin, some other task could still jump in and write it’s own bit to the pin before you wake up. So what you really want to do is unlock the mutex and unwrap all the layers to get just the io pin object, and give ownership of it to the task. Then the task can write to the pin, sleep, and not worry that any other task can write to the pin before it wakes back up. When it comes time to spawn that other task, you can unlock and unwrap another io pin and pass along ownership of it to the new task. Meanwhile the compiler prevents either task from accessing pins not assigned to them, unless they contain the code to unlock the global mutex. But then you have to talk about how to spawn multiple tasks, and I bet that’s in a different chapter! By the end of the book when all the pieces are in place, there probably is no global variable for the IO pins, no task tries to unlock a global mutex, and instead all tasks take ownership of the pins they need.
- mips_r4300i 3y agoThis is the way. You explained it better than I could have. The example being an IO pin toggle is not great, because it's such a simple operation, and typically will be intrinsically atomic on many MCUs. Now, something like setting up a DMA on one of the 2 available DMA engines you may have, and blocking til completion via interrupt, that is complex enough it has a much better justification for the abstraction salad.