Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include <atomic>
  2. #include <algorithm>
  3. #include <utility>
  4. #include <functional>
  5. #include <iostream>
  6. #include <thread>
  7. #include <numeric>
  8. #include <vector>
  9.  
  10. struct worker
  11. {
  12. template <typename T>
  13. worker(T && callable)
  14. : m_thread{
  15. std::move(callable)
  16. }
  17. {
  18. }
  19.  
  20. ~worker()
  21. {
  22. m_thread.join();
  23. }
  24.  
  25. std::thread m_thread;
  26. };
  27.  
  28. #define CACHE_LINE 8
  29. #define MAX_SLOTS (8 * CACHE_LINE)
  30. #define SLOT_MASK (MAX_SLOTS-1)
  31. struct channel
  32. {
  33. volatile uint64_t ridx;
  34. char rx_false_shared_cache_line[64-sizeof(ridx)];
  35. volatile uint64_t widx;
  36. char tx_false_shared_cache_line[64-sizeof(widx)];
  37. volatile uint64_t a[MAX_SLOTS];
  38. };
  39.  
  40. void
  41. write_fifo(volatile struct channel * pb, uint64_t data)
  42. {
  43. /* spin until read pointer moves leaving room for the write to complete */
  44. while(pb->widx == ((pb->ridx-1) & SLOT_MASK))
  45. sched_yield();
  46. /* spin */
  47.  
  48. /* perform the write */
  49. pb->a[pb->widx] = data;
  50. pb->widx = ((pb->widx+1) & SLOT_MASK);
  51. }
  52.  
  53. void
  54. read_fifo(volatile struct channel * pb, uint64_t *data)
  55. {
  56. /* spin until write pointer moves leaving room for the read to complete */
  57. while(pb->widx == pb->ridx)
  58. sched_yield();
  59. /* spin */
  60.  
  61. /* read value that was last written */
  62. *data = pb->a[pb->ridx];
  63. pb->ridx = ((pb->ridx+1) & SLOT_MASK);
  64. }
  65.  
  66. int main()
  67. {
  68. channel chan;
  69. memset(&chan,0,sizeof(chan));
  70.  
  71. auto produced =
  72. std::make_shared<worker>([&chan](){
  73. int i = 0;
  74. while(1){
  75. write_fifo(&chan,i++);
  76. }
  77. });
  78.  
  79. auto consumed =
  80. std::make_shared<worker>([&chan](){
  81. uint64_t data;
  82. while(1){
  83. read_fifo(&chan,&data);
  84. std::cout << data << '\n';
  85. }
  86. });
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement