Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <atomic>
- #include <algorithm>
- #include <utility>
- #include <functional>
- #include <iostream>
- #include <thread>
- #include <numeric>
- #include <vector>
- struct worker
- {
- template <typename T>
- worker(T && callable)
- : m_thread{
- std::move(callable)
- }
- {
- }
- ~worker()
- {
- m_thread.join();
- }
- std::thread m_thread;
- };
- #define CACHE_LINE 8
- #define MAX_SLOTS (8 * CACHE_LINE)
- #define SLOT_MASK (MAX_SLOTS-1)
- struct channel
- {
- volatile uint64_t ridx;
- char rx_false_shared_cache_line[64-sizeof(ridx)];
- volatile uint64_t widx;
- char tx_false_shared_cache_line[64-sizeof(widx)];
- volatile uint64_t a[MAX_SLOTS];
- };
- void
- write_fifo(volatile struct channel * pb, uint64_t data)
- {
- /* spin until read pointer moves leaving room for the write to complete */
- while(pb->widx == ((pb->ridx-1) & SLOT_MASK))
- sched_yield();
- /* spin */
- /* perform the write */
- pb->a[pb->widx] = data;
- pb->widx = ((pb->widx+1) & SLOT_MASK);
- }
- void
- read_fifo(volatile struct channel * pb, uint64_t *data)
- {
- /* spin until write pointer moves leaving room for the read to complete */
- while(pb->widx == pb->ridx)
- sched_yield();
- /* spin */
- /* read value that was last written */
- *data = pb->a[pb->ridx];
- pb->ridx = ((pb->ridx+1) & SLOT_MASK);
- }
- int main()
- {
- channel chan;
- memset(&chan,0,sizeof(chan));
- auto produced =
- std::make_shared<worker>([&chan](){
- int i = 0;
- while(1){
- write_fifo(&chan,i++);
- }
- });
- auto consumed =
- std::make_shared<worker>([&chan](){
- uint64_t data;
- while(1){
- read_fifo(&chan,&data);
- std::cout << data << '\n';
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement