/demo/measure-fail.c

Like fast-writer this program update a value as fast as possible. In parallel there is another thread trying to read the same value. Due to concurrent access many reads will fail, the programm output the percentage of fails.

/*
 * CMX (c) Copyright 2013 CERN
 * This software is distributed under the terms of the GNU Lesser General Public Licence version 3
 * (LGPL Version 3), copied verbatim in the file “COPYING”.
 * In applying this licence, CERN does not waive the privileges and immunities granted to it by virtue of its
 * status as an Intergovernmental Organization or submit itself to any jurisdiction. */
#include <stdio.h>
#include <sched.h>
#include <unistd.h>
#include <assert.h>

#include <pthread.h>

#include <cmw-cmx/shm.h>

int run = 0;
int value_handle = 0;
int read_issued = 0;
int read_failed = 0;
int write_issued = 0;
int write_failed = 0;

cmx_shm * cmx_shm_ptr = NULL;

void * thread_read(void *arg)
{
    cmx_shm_value value;
    while (run == 0)
        sched_yield();

    while (run)
    {
        if (E_CMX_SUCCESS != cmx_shm_get_value_single(cmx_shm_ptr, value_handle, NULL, &value, NULL))
        {
            read_failed++;
        }
        read_issued++;
    }

    return NULL;
}

void * thread_write(void *arg)
{
    cmx_shm_value value;
    while (run == 0)
        sched_yield();
    uint64_t start = cmx_common_current_time_usec();
    for (; write_issued < 100000; write_issued++)
    {
        value._int64 = write_issued;
        if (E_CMX_SUCCESS != cmx_shm_set_value_single(cmx_shm_ptr, value_handle, CMX_TYPE_INT64, &value))
        {
            write_failed++;
        }
    }
    run = 0;
    uint64_t stop = cmx_common_current_time_usec();
    printf("Took %lld microseconds = %lld milliseconds for 100 000 writes\n", (stop - start), (stop - start) / 1000);

    return NULL;
}

int main()
{
    pthread_t t_read, t_write;
    assert(E_CMX_SUCCESS == cmx_shm_create("measure_fail", &cmx_shm_ptr));
    value_handle = cmx_shm_add_value_single(cmx_shm_ptr, CMX_TYPE_INT64, "TestInt64");
    assert(value_handle > 0);

    assert(0==pthread_create(&t_read,NULL, thread_read, NULL));
    assert(0==pthread_create(&t_write, NULL, thread_write, NULL));
    usleep(100000);
    run = 1;
    pthread_join(t_write, NULL);
    pthread_join(t_read, NULL);

    printf("write_issued=%d write_failed=%d => fail: %f%%\n", write_issued, write_failed,
            100 * ((double) write_failed / write_issued));
    printf("read_issued=%d read_failed=%d => fail: %f%%\n", read_issued, read_failed,
            100 * ((double) read_failed / read_issued));
    return 0;
}

Generated on 14 Feb 2014 by  doxygen 1.6.1