Ye Cheng
/
cmsis_rtos_demo_mutex
cmsis rtos demo: mutex
main.cpp
- Committer:
- cnhzcy14
- Date:
- 2013-01-06
- Revision:
- 0:fba50ae123e6
- Child:
- 1:1308d7d6d53e
File content as of revision 0:fba50ae123e6:
#include "mbed.h" #include "cmsis_os.h" Serial debug(USBTX, USBRX); typedef struct { double *a; double *b; double sum; int veclen; } DOTDATA; #define NUMTHRDS 4 #define VECLEN 200 DOTDATA dotstr; osMutexId stdio_mutex; osMutexDef(stdio_mutex); void dotprod(void const *arg) { osThreadId id; int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } osMutexWait(stdio_mutex, osWaitForever); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n",offset,start,end,mysum,dotstr.sum); osMutexRelease(stdio_mutex); id = osThreadGetId(); osThreadTerminate(id); } void t0(void const *argument) {dotprod(argument);} osThreadDef(t0, osPriorityNormal, DEFAULT_STACK_SIZE); void t1(void const *argument) {dotprod(argument);} osThreadDef(t1, osPriorityNormal, DEFAULT_STACK_SIZE); void t2(void const *argument) {dotprod(argument);} osThreadDef(t2, osPriorityNormal, DEFAULT_STACK_SIZE); void t3(void const *argument) {dotprod(argument);} osThreadDef(t3, osPriorityNormal, DEFAULT_STACK_SIZE); int main() { debug.baud(57600); long i; double *a, *b; //void *status; /* Assign storage and initialize values */ a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); for (i=0; i<VECLEN*NUMTHRDS; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = VECLEN; dotstr.a = a; dotstr.b = b; dotstr.sum=0; stdio_mutex = osMutexCreate(osMutex(stdio_mutex)); for(i=0;i<NUMTHRDS;i++) { if(i==0) osThreadCreate(osThread(t0), (void *)i); if(i==1) osThreadCreate(osThread(t1), (void *)i); if(i==2) osThreadCreate(osThread(t2), (void *)i); if(i==3) osThreadCreate(osThread(t3), (void *)i); } printf ("Sum = %f \n", dotstr.sum); free (a); free (b); }