Note that there are some explanatory texts on larger screens.

plurals
  1. POSingle producer single consumer lock free queue c
    text
    copied!<p>I am wondering why it would be incorrect to implement this sort of queue the naive way:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;pthread.h&gt; #include &lt;sys/time.h&gt; void *print_message_function( void *ptr ); void *reader( void *ptr ); void *writer( void *ptr ); int queue[500000]; int main(int argc, char **argv) { pthread_t thread1, thread2; char *message1 = "Thread 1"; char *message2 = "Thread 2"; int iret1, iret2; iret1 = pthread_create( &amp;thread1, NULL, writer, (void*) message1); iret2 = pthread_create( &amp;thread2, NULL, reader, (void*) message2); usleep(2000); void pthread_exit(void *iret1 ); void pthread_exit(void *iret2 ); exit(0); } void *writer( void *ptr ) { // make local copy of queue head register int *pos = queue; // struct thread_param *tp = arg; int counter = 0; while(1) { //Write to head of queue *pos = 5; pos++; print_message_function( ptr); } } void *reader( void *ptr ) { int counter = 0; // make local copy of queue head register int *pos = queue; while(1) { // Read from tail of queue - loop when nothing if ( *pos == 5 ) { print_message_function( ptr ); pos++; } } } void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf("%s \n", message); } </code></pre> <p>I do intend to cache align the queue. </p> <p>I do not believe memory reordering is a problem since a copy of the queue head is made on start and there is a single reader and writer. </p> <p>My reason for wanting this is it should be faster than either mutex locks or CAS ops.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload