rt_benchs/communication_techniques/src/communication/csq.c

111 lines
1.7 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
/* Non standard include */
#include <commtech.h>
#include <specific_comm.h>
__thread struct comm *comm;
__thread union ctrl ctrl __attribute__ ((aligned (CACHE_LINE_SIZE)));
int init_library(void)
{
return 0;
}
int finalize_library(void)
{
return 0;
}
void *create_comm_channel(void)
{
struct comm *comm;
if (!posix_memalign((void *) &comm, CACHE_LINE_SIZE, sizeof(struct comm)))
{
int i;
for (i = 0; i < SLOTS; i++)
comm->queue[i].flag = 0;
return comm;
}
return NULL;
}
int destroy_comm_channel(void *comm)
{
free(comm);
return 0;
}
int init_producer_thread(void *comm_param)
{
comm = (struct comm *) comm_param;
ctrl.tail = 0;
return 0;
}
int finalize_producer_thread(void *unused)
{
comm = NULL;
ctrl.tail = 0;
return 0;
}
int init_consumer_thread(void *comm_param)
{
comm = (struct comm *) comm_param;
ctrl.head = 0;
return 0;
}
int finalize_consumer_thread(void *unused)
{
comm = NULL;
ctrl.head = 0;
return 0;
}
void *recv_one_data(void)
{
static __thread int i;
void *result;
if (__builtin_expect(!i, 0))
while (!comm->queue[ctrl.head].flag);
result = comm->queue[ctrl.head].chunk[i++];
if (i % SUB_SLOTS)
{
i = 0;
comm->queue[ctrl.head].flag = 0;
ctrl.head = (ctrl.head + 1) % SLOTS;
}
return result;
}
ssize_t recv_some_data(void **buf, size_t count)
{
int n;
n = 0;
// If all slots are empty, spin
while (comm->queue[ctrl.head].flag)
{
// Dequeue a chunk of data items
memcpy(buf, (const void *)
comm->queue[ctrl.head].chunk,
SUB_SLOTS * sizeof(*buf));
n += SUB_SLOTS;
comm->queue[ctrl.head].flag = 0;
ctrl.head = (ctrl.head + 1) % SLOTS;
if (n == count)
break;
}
return n;
}