rt_benchs/communication_techniques/src/communication/shared_mem_opt.c

109 lines
2.9 KiB
C

/*
* Copyright (C) 2009-2012 Thomas Preud'homme <thomas.preud-homme@lip6.fr>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
/* Non standard include */
#include <commtech.h>
#include <specific_comm.h>
void *create_comm_channel(void)
{
struct channel *channel;
if (!posix_memalign((void *) &channel, CACHE_LINE_SIZE, sizeof(struct channel)))
{
if (!posix_memalign((void *) &channel->shared_space, CACHE_LINE_SIZE, SHARED_SPACE_SIZE))
{
channel->cons_idx = 0;
channel->prod_idx = 0;
return channel;
}
else
free(channel);
}
return NULL;
}
int end_producer(void *unused __attribute__ ((unused)))
{
return 0;
}
int destroy_comm_channel(void *channel)
{
free((void *) ((struct channel *) channel)->shared_space);
free(channel);
return 0;
}
void *recv_one_data(struct channel *channel)
{
void *result;
unsigned int cons_idx, prod_idx;
cons_idx = channel->cons_idx;
prod_idx = channel->prod_idx;
if (cons_idx == prod_idx)
while(prod_idx == channel->prod_idx);
/*
* The behaviour of this is not documented but we know the
* values inside shared_space won't change during this
* affectation
*/
result = channel->shared_space[cons_idx];
cons_idx = (cons_idx + 1) % SHARED_SPACE_VOIDPTR;
channel->cons_idx = cons_idx;
return result;
}
ssize_t recv_some_data(struct channel *channel, void **buf, size_t count)
{
unsigned int n, cons_idx, prod_idx;
n = 0;
cons_idx = channel->cons_idx;
do
{
prod_idx = channel->prod_idx;
for(; cons_idx != prod_idx; cons_idx = (cons_idx + 1) % SHARED_SPACE_VOIDPTR)
{
/*
* The behaviour of this is not documented but we know
* the values inside buf won't change during this affectation
*/
*buf++ = channel->shared_space[cons_idx];
if (++n == count)
{
channel->cons_idx = cons_idx;
return n;
}
}
} while (prod_idx != channel->prod_idx);
channel->cons_idx = cons_idx;
return n;
}