void ctor() {
	states = Allocator( sizeof(__typeof__(states[0])) * N * PADRATIO);
	for ( int i = 0; i < N; i += 1 ) {					// initialize shared data
		states[i*PADRATIO] = ATOMIC_VAR_INIT(UNLOCKED);
	} // for
	turn = ATOMIC_VAR_INIT(0);
} // ctor
Ejemplo n.º 2
0
void mrqd_delegate_wait(void* lock,
                      void (*funPtr)(unsigned int, void *), 
                      unsigned int messageSize,
                      void * messageAddress) {
    volatile atomic_int waitVar = ATOMIC_VAR_INIT(1);
    unsigned int metaDataSize = sizeof(volatile atomic_int *) + 
        sizeof(void (*)(unsigned int, void *));
    char * buff = mrqd_delegate_or_lock(lock,
                                        metaDataSize + messageSize);
    if(buff==NULL){
        funPtr(messageSize, messageAddress);
        mrqd_delegate_unlock(lock);
    }else{
        volatile atomic_int ** waitVarPtrAddress = (volatile atomic_int **)buff;
        *waitVarPtrAddress = &waitVar;
        void (**funPtrAdress)(unsigned int, void *) = (void (**)(unsigned int, void *))&buff[sizeof(volatile atomic_int *)];
        *funPtrAdress = funPtr;
        unsigned int metaDataSize = sizeof(volatile atomic_int *) + 
            sizeof(void (*)(unsigned int, void *));
        char * msgBuffer = (char *)messageAddress;
        for(unsigned int i = metaDataSize; i < (messageSize + metaDataSize); i++){
            buff[i] = msgBuffer[i - metaDataSize];
        }
        mrqd_close_delegate_buffer((void *)buff, mrqd_executeAndWaitCS);
        while(atomic_load_explicit(&waitVar, memory_order_acquire)){
            thread_yield();
        }
    }
}
Ejemplo n.º 3
0
/////////////////////////////////////////////////////////////////////////
// System Pipe Segment Code
static void
CreateSegment(
    _In_ SystemPipe_t*              Pipe,
    _In_ SystemPipeSegment_t**      Segment,
    _In_ unsigned int               TicketBase)
{
    // Variables
    SystemPipeSegment_t* Pointer;
    size_t BytesToAllocate = sizeof(SystemPipeSegment_t);
    int i;

    // Perform the allocation
    if (Pipe->Configuration & PIPE_STRUCTURED_BUFFER) {
        BytesToAllocate += (sizeof(SystemPipeEntry_t) * TICKETS_PER_SEGMENT(Pipe));
    }
    Pointer         = (SystemPipeSegment_t*)kmalloc(BytesToAllocate);
    assert(Pointer != NULL);
    memset((void*)Pointer, 0, BytesToAllocate);

    InitializeSegmentBuffer(Pipe, &Pointer->Buffer);
    Pointer->TicketBase     = TicketBase;
    if (Pipe->Configuration & PIPE_STRUCTURED_BUFFER) {
        Pointer->ProductionSpots    = ATOMIC_VAR_INIT(TICKETS_PER_SEGMENT(Pipe));
        Pointer->Entries            = (SystemPipeEntry_t*)((uint8_t*)Pointer + sizeof(SystemPipeSegment_t));
        for (i = 0; i < TICKETS_PER_SEGMENT(Pipe); i++) {
            InitializeSegmentEntry(&Pointer->Entries[i]);
        }
    }
    *Segment = Pointer;
}
Ejemplo n.º 4
0
struct mutex *mutex_create(struct mutex *m, unsigned flags)
{
	KOBJ_CREATE(m, flags, MT_ALLOC);
	m->lock = ATOMIC_VAR_INIT(0);
	m->magic = MUTEX_MAGIC;
	blocklist_create(&m->blocklist, 0, "mutex");
	return m;
}
Ejemplo n.º 5
0
static struct json *
jsonrpc_create_id(void)
{
    static atomic_uint next_id = ATOMIC_VAR_INIT(0);
    unsigned int id;

    atomic_add(&next_id, 1, &id);
    return json_integer_create(id);
}
Ejemplo n.º 6
0
static
void ccsynchlock_initNode(CCSynchLockNode * node){
    node->requestFunction = NULL;
    node->messageSize = CCSYNCH_BUFFER_SIZE + 1;
    atomic_store_explicit(&node->wait, 0, memory_order_relaxed);
    node->completed = false;
    volatile atomic_uintptr_t tmp = ATOMIC_VAR_INIT((uintptr_t)NULL);
    node->next = tmp;
}
Ejemplo n.º 7
0
TEST(stdatomic, init) {
  atomic_int v = ATOMIC_VAR_INIT(123);
  ASSERT_EQ(123, atomic_load(&v));

  atomic_init(&v, 456);
  ASSERT_EQ(456, atomic_load(&v));

  atomic_flag f = ATOMIC_FLAG_INIT;
  ASSERT_FALSE(atomic_flag_test_and_set(&f));
}
Ejemplo n.º 8
0
Archivo: main.cpp Proyecto: CCJY/coliru
int main(int argc, char *argv[])
{
    std::vector<std::thread> thrds;
    std::atomic_int a_int = ATOMIC_VAR_INIT(0);
    int raw_int = 0;
    
    unsigned int N = std::thread::hardware_concurrency()+1;
    std::cout << "Using " << N << " threads..." << std::endl;
    std::generate_n(std::back_inserter(thrds), N,
        [&](){return std::thread(foo, std::ref(a_int), std::ref(raw_int));});
    
    std::for_each(thrds.begin(), thrds.end(), [](std::thread& t){ t.join(); });
    
    std::cout << "Non-Atomic: " << raw_int << std::endl;
    std::cout << "Atomic:     " << a_int << std::endl;
    return 0;
}
Ejemplo n.º 9
0
void test() {
    typedef std::atomic<Tp> Atomic;
    static_assert(std::is_literal_type<Atomic>::value, "");
    constexpr Tp t(42);
    {
        constexpr Atomic a(t);
        assert(a == t);
    }
    {
        constexpr Atomic a{t};
        assert(a == t);
    }
    {
        constexpr Atomic a = ATOMIC_VAR_INIT(t);
        assert(a == t);
    }
}
Ejemplo n.º 10
0
static int atomic(void)
{
	atomic_int counter = ATOMIC_VAR_INIT(0);
	int value, error=0, i;

	for (i = 0; i < atomic_test_count; i++) {
		atomic_fetch_add(&counter, 1);
	}

	value = atomic_load(&counter);
	value -= atomic_test_count;
	if (value) {
		metal_log(METAL_LOG_DEBUG, "counter mismatch, delta = %d\n", value);
		error = -1;
	}

	return error;
}
Ejemplo n.º 11
0
TEST(stdatomic, atomic_fetch_sub) {
  atomic_int i = ATOMIC_VAR_INIT(123);
  ASSERT_EQ(123, atomic_fetch_sub(&i, 1));
  ASSERT_EQ(122, atomic_fetch_sub_explicit(&i, 1, memory_order_relaxed));
  ASSERT_EQ(121, atomic_load(&i));
}
Ejemplo n.º 12
0
#include "stdafx.h"

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <sys/types.h>
#include <sys/sem.h>

std::atomic_int isWaiting = ATOMIC_VAR_INIT(0);
std::condition_variable condVar;
std::mutex mutex;

void stepRight() {
	std::unique_lock<std::mutex> lock(mutex);
	for (int i = 0; i < 10; ++i) {
		std::cout << "right" << std::endl;
		isWaiting.fetch_add(1);
		if (isWaiting.load() % 2 != 1) {
			condVar.notify_one();
		}
		else {
			condVar.wait(lock);
		}
	}
}
void stepLeft() {
	std::unique_lock<std::mutex> lock(mutex);
	for (int i = 0; i < 10; ++i) {
Ejemplo n.º 13
0
// atomic_signal_fence_ex.c : atomic_signal_fence() example
// -------------------------------------------------------------

#include <stdatomic.h>  
// void atomic_signal_fence( memory_order order);

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <stdatomic.h>

static_assert(ATOMIC_INT_LOCK_FREE == 2,
              "atomic_int must be lock-free in the signal handler.");

atomic_int guide = ATOMIC_VAR_INIT(0),
           data = ATOMIC_VAR_INIT(0);

void SIGTERM_handler(int sig)
{
    if( atomic_load_explicit( &guide, memory_order_relaxed) == 1)
    {
       atomic_signal_fence(memory_order_acquire);
       int d = atomic_load_explicit( &data, memory_order_relaxed);
       assert(d == 100);               // Condition fulfilled!
    // ...
    }
    _Exit(0);
}

int main(void)
Ejemplo n.º 14
0
#include <arch/utils.h>
#include <interrupts.h>
#include <memory.h>
#include <assert.h>
#include <string.h>
#include <arch.h>
#include <heap.h>
#include <gdt.h>

extern void TssInstall(int GdtIndex);

GdtObject_t __GdtTableObject; // Don't make static, used in asm
static GdtDescriptor_t Descriptors[GDT_MAX_DESCRIPTORS] = { { 0 } };
static TssDescriptor_t *TssPointers[GDT_MAX_TSS]        = { 0 };
static TssDescriptor_t BootTss                          = { 0 };
static _Atomic(int) GdtIndicer                          = ATOMIC_VAR_INIT(0);

static int
GdtInstallDescriptor(
    _In_ uint64_t Base, 
    _In_ uint32_t Limit,
    _In_ uint8_t  Access, 
    _In_ uint8_t  Grandularity)
{
    int GdtIndex = atomic_fetch_add(&GdtIndicer, 1);

	// Fill descriptor
	Descriptors[GdtIndex].BaseLow   = (uint16_t)(Base & 0xFFFF);
	Descriptors[GdtIndex].BaseMid   = (uint8_t)((Base >> 16) & 0xFF);
	Descriptors[GdtIndex].BaseHigh  = (uint8_t)((Base >> 24) & 0xFF);
	Descriptors[GdtIndex].BaseUpper = (uint32_t)((Base >> 32) & 0xFFFFFFFF);
Ejemplo n.º 15
0
#include <fstream> // PZ
#include <uhd/utils/thread_priority.hpp>
#include <uhd/utils/safe_main.hpp>
#include <uhd/usrp/multi_usrp.hpp>
#include <uhd/device.hpp>
#include <boost/program_options.hpp>
#include <boost/format.hpp>
#include <iostream>
#include <complex>
#include <uhd/types/clock_config.hpp>
//#include <gruel/realtime.h>
#include <atomic>
extern double dummy_float;


std::atomic<int> counter = ATOMIC_VAR_INIT(0);



// The square_elements_of_array is defined in another file (normally in *.hpp file):
extern void square_elements_of_array(float data_to_harness[],int no_elements) ;

namespace po = boost::program_options;

int UHD_SAFE_MAIN(int argc, char *argv[]){
    
  #if 0
    if (!(uhd::set_thread_priority_safe(1,true))) {
      std::cout << "Problem setting thread priority" << std::endl;
      return 1;
    };
Ejemplo n.º 16
0
TEST(stdatomic, atomic_fetch_xor) {
  atomic_int i = ATOMIC_VAR_INIT(0x100);
  ASSERT_EQ(0x100, atomic_fetch_xor(&i, 0x120));
  ASSERT_EQ(0x020, atomic_fetch_xor_explicit(&i, 0x103, memory_order_relaxed));
  ASSERT_EQ(0x123, atomic_load(&i));
}
Ejemplo n.º 17
0
#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <chrono>
 
std::condition_variable cv;
std::mutex cv_m;
std::atomic<int> i = ATOMIC_VAR_INIT(0);
 
void waits(int idx)
{
    std::unique_lock<std::mutex> lk(cv_m);
    auto now = std::chrono::system_clock::now();
    if(cv.wait_until(lk, now + std::chrono::milliseconds(idx*100), [](){return i == 1;}))
        std::cerr << "Thread " << idx << " finished waiting. i == " << i << '\n';
    else
        std::cerr << "Thread " << idx << " timed out. i == " << i << '\n';
}
 
void signals()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(120));
    std::cerr << "Notifying...\n";
    cv.notify_all();
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    i = 1;
    std::cerr << "Notifying again...\n";
    cv.notify_all();
}
 
Ejemplo n.º 18
0
/* VLF_FILE configuration.
 *
 * All of the following is protected by 'log_file_mutex', which nests inside
 * pattern_rwlock. */
static struct ovs_mutex log_file_mutex = OVS_MUTEX_INITIALIZER;
static char *log_file_name OVS_GUARDED_BY(log_file_mutex);
static int log_fd OVS_GUARDED_BY(log_file_mutex) = -1;
static struct async_append *log_writer OVS_GUARDED_BY(log_file_mutex);
static bool log_async OVS_GUARDED_BY(log_file_mutex);

/* Syslog export configuration. */
static int syslog_fd OVS_GUARDED_BY(pattern_rwlock) = -1;

/* Log facility configuration. */
static atomic_int log_facility = ATOMIC_VAR_INIT(0);

/* Facility name and its value. */
struct vlog_facility {
    char *name;           /* Name. */
    unsigned int value;   /* Facility associated with 'name'. */
};
static struct vlog_facility vlog_facilities[] = {
    {"kern", LOG_KERN},
    {"user", LOG_USER},
    {"mail", LOG_MAIL},
    {"daemon", LOG_DAEMON},
    {"auth", LOG_AUTH},
    {"syslog", LOG_SYSLOG},
    {"lpr", LOG_LPR},
    {"news", LOG_NEWS},
Ejemplo n.º 19
0
// Copyright (c) 2016 Nuxi, https://nuxi.nl/
//
// This file is distributed under a 2-clause BSD license.
// See the LICENSE file for details.

#include <common/pthread.h>

#include <stdatomic.h>
#include <stddef.h>

_Atomic(struct thread_atexit *) __thread_atexit_last = ATOMIC_VAR_INIT(NULL);
Ejemplo n.º 20
0
/*
 * Global variables
 */
int *array1;

pthread_mutex_t pmutex;
ticket_mutex_t ticketmutex;
tidex_mutex_t tidexmutex;


#define TYPE_PTHREAD_MUTEX        0
#define TYPE_TICKET_MUTEX         3
#define TYPE_TIDEX_MUTEX          5


atomic_int g_quit = ATOMIC_VAR_INIT(0);
// These two don't have to be atomic because they are set before the threads are created or read after the threads join
int g_which_lock = TYPE_PTHREAD_MUTEX;
int g_operCounters[NUM_THREADS];


static void clearOperCounters(void) {
    int i;
    for (i = 0; i < NUM_THREADS; i++) g_operCounters[i] = 0;
}

static void printOperationsPerSecond() {
    int i;
    long sum = 0;
    for (i = 0; i < NUM_THREADS; i++) sum += g_operCounters[i];
    printf("Operations/sec = %d\n", sum);
Ejemplo n.º 21
0
#include <thread>
#include <atomic>
#include <cassert>
#include <iostream>

std::atomic<bool> x = ATOMIC_VAR_INIT(false);
std::atomic<bool> y = ATOMIC_VAR_INIT(false);
std::atomic<int> z = ATOMIC_VAR_INIT(0);

void write_x()
{
	// x.store(true, std::memory_order_seq_cst);
	// x.store(true, std::memory_order_release);
	x.store(true, std::memory_order_relaxed);
}

void write_y()
{
	// y.store(true, std::memory_order_seq_cst);
	// y.store(true, std::memory_order_release);
	y.store(true, std::memory_order_relaxed);
}

void read_x_then_y()
{
	// while (!x.load(std::memory_order_seq_cst));
	// while (!x.load(std::memory_order_acquire));
	while (!x.load(std::memory_order_relaxed));

	// if (y.load(std::memory_order_seq_cst)) ++z;
	// if (y.load(std::memory_order_acquire)) ++z;
Ejemplo n.º 22
0
namespace WTF {

static Variant<TextBreakIteratorICU, TextBreakIteratorPlatform> mapModeToBackingIterator(StringView string, TextBreakIterator::Mode mode, const AtomicString& locale)
{
    switch (mode) {
    case TextBreakIterator::Mode::Line:
        return TextBreakIteratorICU(string, TextBreakIteratorICU::Mode::Line, locale.string().utf8().data());
    case TextBreakIterator::Mode::Caret:
        return TextBreakIteratorICU(string, TextBreakIteratorICU::Mode::Character, locale.string().utf8().data());
    case TextBreakIterator::Mode::Delete:
        return TextBreakIteratorICU(string, TextBreakIteratorICU::Mode::Character, locale.string().utf8().data());
    default:
        ASSERT_NOT_REACHED();
        return TextBreakIteratorICU(string, TextBreakIteratorICU::Mode::Character, locale.string().utf8().data());
    }
}

TextBreakIterator::TextBreakIterator(StringView string, Mode mode, const AtomicString& locale)
    : m_backing(mapModeToBackingIterator(string, mode, locale))
    , m_mode(mode)
    , m_locale(locale)
{
}

// Iterator initialization

static UBreakIterator* initializeIterator(UBreakIteratorType type, const char* locale = currentTextBreakLocaleID())
{
    UErrorCode openStatus = U_ZERO_ERROR;
    UBreakIterator* iterator = ubrk_open(type, locale, 0, 0, &openStatus);
    ASSERT_WITH_MESSAGE(U_SUCCESS(openStatus), "ICU could not open a break iterator: %s (%d)", u_errorName(openStatus), openStatus);
    return iterator;
}

// Iterator text setting

static UBreakIterator* setTextForIterator(UBreakIterator& iterator, StringView string)
{
    if (string.is8Bit()) {
        UTextWithBuffer textLocal;
        textLocal.text = UTEXT_INITIALIZER;
        textLocal.text.extraSize = sizeof(textLocal.buffer);
        textLocal.text.pExtra = textLocal.buffer;

        UErrorCode openStatus = U_ZERO_ERROR;
        UText* text = openLatin1UTextProvider(&textLocal, string.characters8(), string.length(), &openStatus);
        if (U_FAILURE(openStatus)) {
            LOG_ERROR("uTextOpenLatin1 failed with status %d", openStatus);
            return nullptr;
        }

        UErrorCode setTextStatus = U_ZERO_ERROR;
        ubrk_setUText(&iterator, text, &setTextStatus);
        if (U_FAILURE(setTextStatus)) {
            LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
            return nullptr;
        }

        utext_close(text);
    } else {
        UErrorCode setTextStatus = U_ZERO_ERROR;
        ubrk_setText(&iterator, string.characters16(), string.length(), &setTextStatus);
        if (U_FAILURE(setTextStatus))
            return nullptr;
    }

    return &iterator;
}

static UBreakIterator* setContextAwareTextForIterator(UBreakIterator& iterator, StringView string, const UChar* priorContext, unsigned priorContextLength)
{
    if (string.is8Bit()) {
        UTextWithBuffer textLocal;
        textLocal.text = UTEXT_INITIALIZER;
        textLocal.text.extraSize = sizeof(textLocal.buffer);
        textLocal.text.pExtra = textLocal.buffer;

        UErrorCode openStatus = U_ZERO_ERROR;
        UText* text = openLatin1ContextAwareUTextProvider(&textLocal, string.characters8(), string.length(), priorContext, priorContextLength, &openStatus);
        if (U_FAILURE(openStatus)) {
            LOG_ERROR("openLatin1ContextAwareUTextProvider failed with status %d", openStatus);
            return nullptr;
        }

        UErrorCode setTextStatus = U_ZERO_ERROR;
        ubrk_setUText(&iterator, text, &setTextStatus);
        if (U_FAILURE(setTextStatus)) {
            LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
            return nullptr;
        }

        utext_close(text);
    } else {
        UText textLocal = UTEXT_INITIALIZER;

        UErrorCode openStatus = U_ZERO_ERROR;
        UText* text = openUTF16ContextAwareUTextProvider(&textLocal, string.characters16(), string.length(), priorContext, priorContextLength, &openStatus);
        if (U_FAILURE(openStatus)) {
            LOG_ERROR("openUTF16ContextAwareUTextProvider failed with status %d", openStatus);
            return 0;
        }

        UErrorCode setTextStatus = U_ZERO_ERROR;
        ubrk_setUText(&iterator, text, &setTextStatus);
        if (U_FAILURE(setTextStatus)) {
            LOG_ERROR("ubrk_setUText failed with status %d", setTextStatus);
            return nullptr;
        }

        utext_close(text);
    }

    return &iterator;
}


// Static iterators

UBreakIterator* wordBreakIterator(StringView string)
{
    static UBreakIterator* staticWordBreakIterator = initializeIterator(UBRK_WORD);
    if (!staticWordBreakIterator)
        return nullptr;

    return setTextForIterator(*staticWordBreakIterator, string);
}

UBreakIterator* sentenceBreakIterator(StringView string)
{
    static UBreakIterator* staticSentenceBreakIterator = initializeIterator(UBRK_SENTENCE);
    if (!staticSentenceBreakIterator)
        return nullptr;

    return setTextForIterator(*staticSentenceBreakIterator, string);
}

UBreakIterator* acquireLineBreakIterator(StringView string, const AtomicString& locale, const UChar* priorContext, unsigned priorContextLength, LineBreakIteratorMode mode)
{
    UBreakIterator* iterator = LineBreakIteratorPool::sharedPool().take(locale, mode);
    if (!iterator)
        return nullptr;

    return setContextAwareTextForIterator(*iterator, string, priorContext, priorContextLength);
}

void releaseLineBreakIterator(UBreakIterator* iterator)
{
    ASSERT_ARG(iterator, iterator);

    LineBreakIteratorPool::sharedPool().put(iterator);
}

UBreakIterator* openLineBreakIterator(const AtomicString& locale)
{
    bool localeIsEmpty = locale.isEmpty();
    UErrorCode openStatus = U_ZERO_ERROR;
    UBreakIterator* ubrkIter = ubrk_open(UBRK_LINE, localeIsEmpty ? currentTextBreakLocaleID() : locale.string().utf8().data(), 0, 0, &openStatus);
    // locale comes from a web page and it can be invalid, leading ICU
    // to fail, in which case we fall back to the default locale.
    if (!localeIsEmpty && U_FAILURE(openStatus)) {
        openStatus = U_ZERO_ERROR;
        ubrkIter = ubrk_open(UBRK_LINE, currentTextBreakLocaleID(), 0, 0, &openStatus);
    }

    if (U_FAILURE(openStatus)) {
        LOG_ERROR("ubrk_open failed with status %d", openStatus);
        return nullptr;
    }

    return ubrkIter;
}

void closeLineBreakIterator(UBreakIterator*& iterator)
{
    UBreakIterator* ubrkIter = iterator;
    ASSERT(ubrkIter);
    ubrk_close(ubrkIter);
    iterator = nullptr;
}

static std::atomic<UBreakIterator*> nonSharedCharacterBreakIterator = ATOMIC_VAR_INIT(nullptr);

static inline UBreakIterator* getNonSharedCharacterBreakIterator()
{
    if (auto *res = nonSharedCharacterBreakIterator.exchange(nullptr, std::memory_order_acquire))
        return res;
    return initializeIterator(UBRK_CHARACTER);
}

static inline void cacheNonSharedCharacterBreakIterator(UBreakIterator* cacheMe)
{
    if (auto *old = nonSharedCharacterBreakIterator.exchange(cacheMe, std::memory_order_release))
        ubrk_close(old);
}

NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(StringView string)
{
    if ((m_iterator = getNonSharedCharacterBreakIterator()))
        m_iterator = setTextForIterator(*m_iterator, string);
}

NonSharedCharacterBreakIterator::~NonSharedCharacterBreakIterator()
{
    if (m_iterator)
        cacheNonSharedCharacterBreakIterator(m_iterator);
}

NonSharedCharacterBreakIterator::NonSharedCharacterBreakIterator(NonSharedCharacterBreakIterator&& other)
    : m_iterator(nullptr)
{
    std::swap(m_iterator, other.m_iterator);
}

// Iterator implemenation.

bool isWordTextBreak(UBreakIterator* iterator)
{
    int ruleStatus = ubrk_getRuleStatus(iterator);
    return ruleStatus != UBRK_WORD_NONE;
}

unsigned numGraphemeClusters(StringView string)
{
    unsigned stringLength = string.length();
    
    if (!stringLength)
        return 0;

    // The only Latin-1 Extended Grapheme Cluster is CRLF.
    if (string.is8Bit()) {
        auto* characters = string.characters8();
        unsigned numCRLF = 0;
        for (unsigned i = 1; i < stringLength; ++i)
            numCRLF += characters[i - 1] == '\r' && characters[i] == '\n';
        return stringLength - numCRLF;
    }

    NonSharedCharacterBreakIterator iterator { string };
    if (!iterator) {
        ASSERT_NOT_REACHED();
        return stringLength;
    }

    unsigned numGraphemeClusters = 0;
    while (ubrk_next(iterator) != UBRK_DONE)
        ++numGraphemeClusters;
    return numGraphemeClusters;
}

unsigned numCodeUnitsInGraphemeClusters(StringView string, unsigned numGraphemeClusters)
{
    unsigned stringLength = string.length();

    if (stringLength <= numGraphemeClusters)
        return stringLength;

    // The only Latin-1 Extended Grapheme Cluster is CRLF.
    if (string.is8Bit()) {
        auto* characters = string.characters8();
        unsigned i, j;
        for (i = 0, j = 0; i < numGraphemeClusters && j + 1 < stringLength; ++i, ++j)
            j += characters[j] == '\r' && characters[j + 1] == '\n';
        return j + (i < numGraphemeClusters);
    }

    NonSharedCharacterBreakIterator iterator { string };
    if (!iterator) {
        ASSERT_NOT_REACHED();
        return stringLength;
    }

    for (unsigned i = 0; i < numGraphemeClusters; ++i) {
        if (ubrk_next(iterator) == UBRK_DONE)
            return stringLength;
    }
    return ubrk_current(iterator);
}

} // namespace WTF
Ejemplo n.º 23
0
EasyTreeWidgetLoader::EasyTreeWidgetLoader() : m_bDone(ATOMIC_VAR_INIT(false)), m_bInterrupt(ATOMIC_VAR_INIT(false)), m_progress(ATOMIC_VAR_INIT(0))
{
}
Ejemplo n.º 24
0
TEST(stdatomic, atomic_fetch_and) {
  atomic_int i = ATOMIC_VAR_INIT(0x123);
  ASSERT_EQ(0x123, atomic_fetch_and(&i, 0x00f));
  ASSERT_EQ(0x003, atomic_fetch_and_explicit(&i, 0x2, memory_order_relaxed));
  ASSERT_EQ(0x002, atomic_load(&i));
}
Ejemplo n.º 25
0
#include "arch/atomic.h"
#include "lpelcfg.h"
#include "decen_task.h"

#include "decen_stream.h"
#include "lpel/monitor.h"

//#define _USE_STREAM_DBG__

#ifdef _USE_STREAM_DBG__
#define STREAM_DBG printf
#else
#define STREAM_DBG	//
#endif

static atomic_int stream_seq = ATOMIC_VAR_INIT(0);

/**
 * Create a stream
 *
 * Allocate and initialize memory for a stream.
 *
 * @return pointer to the created stream
 */
lpel_stream_t *LpelStreamCreate(int size)
{
  assert( size >= 0);
  if (0==size) size = STREAM_BUFFER_SIZE;

  /* allocate memory for both the stream struct and the buffer area */
  lpel_stream_t *s = (lpel_stream_t *) malloc( sizeof(lpel_stream_t) );
Ejemplo n.º 26
0
#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "ext/nets.h"

#include <libcaer/events/common.h>

#include <signal.h>
#include <stdatomic.h>

static atomic_bool globalShutdown = ATOMIC_VAR_INIT(false);

static void globalShutdownSignalHandler(int signal) {
	// Simply set the running flag to false on SIGTERM and SIGINT (CTRL+C) for global shutdown.
	if (signal == SIGTERM || signal == SIGINT) {
		atomic_store(&globalShutdown, true);
	}
}

int main(int argc, char *argv[]) {
	// Install signal handler for global shutdown.
	struct sigaction shutdownAction;

	shutdownAction.sa_handler = &globalShutdownSignalHandler;
	shutdownAction.sa_flags = 0;
	sigemptyset(&shutdownAction.sa_mask);
Ejemplo n.º 27
0
#include <string.h>
#include <sys/types.h>

#include <android/log.h>
#include <cutils/compiler.h>
#include <cutils/properties.h>
#include <cutils/trace.h>

/**
 * Maximum size of a message that can be logged to the trace buffer.
 * Note this message includes a tag, the pid, and the string given as the name.
 * Names should be kept short to get the most use of the trace buffer.
 */
#define ATRACE_MESSAGE_LENGTH 1024

atomic_bool             atrace_is_ready      = ATOMIC_VAR_INIT(false);
int                     atrace_marker_fd     = -1;
uint64_t                atrace_enabled_tags  = ATRACE_TAG_NOT_READY;
static bool             atrace_is_debuggable = false;
static atomic_bool      atrace_is_enabled    = ATOMIC_VAR_INIT(true);
static pthread_once_t   atrace_once_control  = PTHREAD_ONCE_INIT;
static pthread_mutex_t  atrace_tags_mutex    = PTHREAD_MUTEX_INITIALIZER;

// Set whether this process is debuggable, which determines whether
// application-level tracing is allowed when the ro.debuggable system property
// is not set to '1'.
void atrace_set_debuggable(bool debuggable)
{
    atrace_is_debuggable = debuggable;
    atrace_update_tags();
}
Ejemplo n.º 28
0
volatile int __kmp_init_middle = FALSE;
volatile int __kmp_init_parallel = FALSE;
#if KMP_USE_MONITOR
volatile int __kmp_init_monitor =
    0; /* 1 - launched, 2 - actually started (Windows* OS only) */
#endif
volatile int __kmp_init_user_locks = FALSE;

/* list of address of allocated caches for commons */
kmp_cached_addr_t *__kmp_threadpriv_cache_list = NULL;

int __kmp_init_counter = 0;
int __kmp_root_counter = 0;
int __kmp_version = 0;

std::atomic<kmp_int32> __kmp_team_counter = ATOMIC_VAR_INIT(0);
std::atomic<kmp_int32> __kmp_task_counter = ATOMIC_VAR_INIT(0);

unsigned int __kmp_init_wait =
    KMP_DEFAULT_INIT_WAIT; /* initial number of spin-tests   */
unsigned int __kmp_next_wait =
    KMP_DEFAULT_NEXT_WAIT; /* susequent number of spin-tests */

size_t __kmp_stksize = KMP_DEFAULT_STKSIZE;
#if KMP_USE_MONITOR
size_t __kmp_monitor_stksize = 0; // auto adjust
#endif
size_t __kmp_stkoffset = KMP_DEFAULT_STKOFFSET;
int __kmp_stkpadding = KMP_MIN_STKPADDING;

size_t __kmp_malloc_pool_incr = KMP_DEFAULT_MALLOC_POOL_INCR;
Ejemplo n.º 29
0
void ctor() {
    assert( N == 2 );
    *intents[0] = ATOMIC_VAR_INIT(DontWantIn);
    *intents[1] = ATOMIC_VAR_INIT(DontWantIn);
    *last = ATOMIC_VAR_INIT(0);
} // ctor
Ejemplo n.º 30
0
*
*   Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/

#include "raylib.h"

#include "pthread.h"                        // POSIX style threads management

#include <stdatomic.h>                      // C11 atomic data types

#include <time.h>                           // Required for: clock()

// Using C11 atomics for synchronization
// NOTE: A plain bool (or any plain data type for that matter) can't be used for inter-thread synchronization
static atomic_bool dataLoaded = ATOMIC_VAR_INIT(false); // Data Loaded completion indicator
static void *LoadDataThread(void *arg);     // Loading data thread function declaration

static int dataProgress = 0;                // Data progress accumulator

int main(void)
{
    // Initialization
    //--------------------------------------------------------------------------------------
    const int screenWidth = 800;
    const int screenHeight = 450;

    InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread");

    pthread_t threadId;             // Loading data thread id