我想知道为什么以天真的方式实现这种队列是不正确的:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
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( &thread1, NULL, writer, (void*) message1);
iret2 = pthread_create( &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);
}
我确实打算缓存对齐队列。
我不相信内存重新排序是一个问题,因为队列头的副本是在开始时制作的,并且只有一个读取器和写入器。
我想要这个的原因是它应该比互斥锁或 CAS 操作更快。