spsc-bugfix: duplicate the (buggy) spsc-queue
[model-checker-benchmarks.git] / mpmc-queue / mpmc-queue.h
1 #include <stdatomic.h>
2 #include <unrelacy.h>
3
4 template <typename t_element, size_t t_size>
5 struct mpmc_boundq_1_alt
6 {
7 private:
8
9         // elements should generally be cache-line-size padded :
10         t_element               m_array[t_size];
11
12         // rdwr counts the reads & writes that have started
13         atomic<unsigned int>    m_rdwr;
14         // "read" and "written" count the number completed
15         atomic<unsigned int>    m_read;
16         atomic<unsigned int>    m_written;
17
18 public:
19
20         mpmc_boundq_1_alt()
21         {
22                 m_rdwr = 0;
23                 m_read = 0;
24                 m_written = 0;
25         }
26
27         //-----------------------------------------------------
28
29         t_element * read_fetch() {
30                 unsigned int rdwr = m_rdwr.load(mo_acquire);
31                 unsigned int rd,wr;
32                 for(;;) {
33                         rd = (rdwr>>16) & 0xFFFF;
34                         wr = rdwr & 0xFFFF;
35
36                         if ( wr == rd ) // empty
37                                 return false;
38
39                         if ( m_rdwr.compare_exchange_weak(rdwr,rdwr+(1<<16),mo_acq_rel) )
40                                 break;
41                 }
42
43                 // (*1)
44                 rl::backoff bo;
45                 while ( (m_written.load(mo_acquire) & 0xFFFF) != wr ) {
46                         bo.yield();
47                 }
48
49                 t_element * p = & ( m_array[ rd % t_size ] );
50
51                 return p;
52         }
53
54         void read_consume() {
55                 m_read.fetch_add(1,mo_release);
56         }
57
58         //-----------------------------------------------------
59
60         t_element * write_prepare() {
61                 unsigned int rdwr = m_rdwr.load(mo_acquire);
62                 unsigned int rd,wr;
63                 for(;;) {
64                         rd = (rdwr>>16) & 0xFFFF;
65                         wr = rdwr & 0xFFFF;
66
67                         if ( wr == ((rd + t_size)&0xFFFF) ) // full
68                                 return NULL;
69
70                         if ( m_rdwr.compare_exchange_weak(rdwr,(rd<<16) | ((wr+1)&0xFFFF),mo_acq_rel) )
71                                 break;
72                 }
73
74                 // (*1)
75                 rl::backoff bo;
76                 while ( (m_read.load(mo_acquire) & 0xFFFF) != rd ) {
77                         bo.yield();
78                 }
79
80                 t_element * p = & ( m_array[ wr % t_size ] );
81
82                 return p;
83         }
84
85         void write_publish()
86         {
87                 m_written.fetch_add(1,mo_release);
88         }
89
90         //-----------------------------------------------------
91
92
93 };