STM32 Discovery Sharing variables between threads

685 views Asked by At

I am new to stack Exchange community. I am trying to share the values of strings between two threads. A portion of the code has been shown below. both contents of waveplayer.c and main.c and declared as a thread each. And the string buffer1 needs to be shared between two threads.

i have declared the as extern.

Please help find a solution

thank u.

//waveplayer.c

uint16_t buffer1[_MAX_SS] ={0x00};
 uint16_t buffer2[_MAX_SS] ={0x00};

extern FATFS fatfs;
 extern FIL file;
 extern FIL fileR;
 extern DIR dir; 

f_lseek(&fileR, WaveCounter);
  f_read (&fileR, buffer1, _MAX_SS, &BytesRead); 

//main.c

void USART3_SendDATA(void const *argument)
{
    while(1)
    {

//  USART_SendData(USART3, 'X');


    if(flagbuffer1)
        {
          f_read (&fileR, buffer1, _MAX_SS, &BytesRead);
            for( j = 0; j< _MAX_SS; j++ )
            USART_SendData(USART3, buffer1[j]);

            flagbuffer1 = 0;
        }

        osThreadYield();
    }

}
1

There are 1 answers

1
tonysdg On

Declare buffer1 as a value on the heap, and define it in one particular file. For example:

/* In common.h file */
extern uint16_t *buffer1;

/* In main.c */
#include "common.h"

extern uint16_t *buffer1;

int main(int argc, char **argv) {
    //your code here
    buffer1 = (uint16_t *)malloc(sizeof(uint16_t) * _MAX_SS);
    //thread starts AFTER this
}

/* In waveplayer.c */
#include "common.h"

extern uint16_t *buffer1;

int foo(...) {
    //use buffer1 here
}

It's worth mentioning that (1) this will only work if the OS you're using supports malloc (if not, I'm not sure how to do this); and (2) you're probably going to need to use mutexes or semaphores if you need different threads to access this buffer. For example:

/* In waveplayer.c */
int foo(...) {
    //acquire mutex here
    //use buffer1 here
    //release mutex here
}

For more information on mutexes, check out an article such as this one: http://www.thegeekstuff.com/2012/05/c-mutex-examples/