From d85852ea510d50e2d0d5634eba264f12b8d45984 Mon Sep 17 00:00:00 2001 From: Wolfgang Hottgenroth Date: Fri, 4 Oct 2019 14:48:57 +0200 Subject: [PATCH] protect counter variables --- snippets/test1/test1.c | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/snippets/test1/test1.c b/snippets/test1/test1.c index fbd0f5a..aaf302a 100644 --- a/snippets/test1/test1.c +++ b/snippets/test1/test1.c @@ -65,6 +65,7 @@ uint32_t counter = 0; uint32_t diff = 0; +pthread_mutex_t counterMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t eventMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t eventSignal = PTHREAD_COND_INITIALIZER; @@ -101,11 +102,14 @@ void isr() { uint32_t currentCounter = read32(CMD_RD | REG_OTR); + pthread_mutex_lock(&counterMutex); diff = currentCounter - lastCounter; counter = currentCounter; - lastCounter = currentCounter; - ec++; + pthread_mutex_unlock(&counterMutex); + + + lastCounter = currentCounter; pthread_mutex_lock(&eventMutex); pthread_cond_signal(&eventSignal); @@ -132,6 +136,9 @@ void initCounter() { int main (void) { static uint32_t lastDiff = 0; + uint32_t my_ec = 0; + uint32_t my_counter = 0; + uint32_t my_diff = 0; init(); initCounter(); @@ -141,6 +148,12 @@ int main (void) { pthread_cond_wait(&eventSignal, &eventMutex); pthread_mutex_unlock(&eventMutex); + pthread_mutex_lock(&counterMutex); + my_ec = ec; + my_counter = counter; + my_diff = diff; + pthread_mutex_unlock(&counterMutex); + if (diff != lastDiff) { lastDiff = diff; double f = 1.0 / (((double) diff) / 1000000.0);