Stanislav Kirichenko’s Post

Easy communication between threads? I present you the 𝗗𝗮𝘁𝗮 𝗼𝗿𝗶𝗲𝗻𝘁𝗲𝗱 𝗰𝗼𝗺𝗺𝗮𝗻𝗱 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝗳𝗼𝗿 𝗺𝘂𝗹𝘁𝗶𝘁𝗵𝗿𝗲𝗮𝗱 𝘀𝗶𝗻𝗴𝗹𝗲-𝗽𝗿𝗼𝗱𝘂𝗰𝗲𝗿-𝘀𝗶𝗻𝗴𝗹𝗲-𝗰𝗼𝗻𝘀𝘂𝗺𝗲𝗿 𝗰𝗼𝗺𝗺𝘂𝗻𝗶𝗰𝗮𝘁𝗶𝗼𝗻. The pattern can be implemented in all low level languages from C, modern C++, Rust, Zig, using templates, unions, polymorphism or std::variant, type erasure etc...  Every problem requires a different specific solution, thus a different implementation. My version compared to the standard 𝗖𝗼𝗺𝗺𝗮𝗻𝗱 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 with virtual functions, it eliminates the overhead of the 𝗩𝗧𝗮𝗯𝗹𝗲 𝗱𝗶𝘀𝗽𝗮𝘁𝗰𝗵, where if the vtable is not already in cache you hit a 𝗰𝗮𝗰𝗵𝗲 𝗺𝗶𝘀𝘀, losing many precious clock cycles, (bad for RTOS or real time renderers). This pattern is perfect to pair with a 𝗹𝗼𝗰𝗸-𝗳𝗿𝗲𝗲 𝗿𝗶𝗻𝗴 𝗯𝘂𝗳𝗳𝗲𝗿 or 𝗾𝘂𝗲𝘂𝗲, one way communication between threads, The command pattern AFAIK is also heavily used in Job/Task systems. I've personally used it in my 𝗩𝘂𝗹𝗸𝗮𝗻 𝗿𝗲𝗻𝗱𝗲𝗿𝗲𝗿 on a dedicated thread, no locks, no mutex, no race conditions, it makes the coding experience easier. Of course there are also drawbacks compared, more boiler plate code, or heavy use of templates to make it more generalized, make a struct for each new command type, etc... It helped me gain 𝗮𝘁 𝗹𝗲𝗮𝘀𝘁 𝟱𝟬𝟬𝗳𝗽𝘀 to switch to another thread without too much hassle. If you think about it, if we could move the ownership of everything from a thread to another one, would this make multithreading easier to write? Save this post and give it a try! #programming #coding #C++

To view or add a comment, sign in

Explore content categories