An example of running multiple thread instances of the same function. Memory is being allocated dynamically.

Dependencies:   Threads mbed-rtos mbed

Committer:
lemniskata
Date:
Sat Jun 29 21:18:14 2013 +0000
Revision:
1:458d82e37147
Parent:
0:06fdc09661c2
Child:
3:681b2f7e1b41
An example of running multiple thread instances of the same function. Memory is being allocated dynamically.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
lemniskata 0:06fdc09661c2 1 #include "mbed.h"
lemniskata 0:06fdc09661c2 2 #include "Threads.h"
lemniskata 0:06fdc09661c2 3
lemniskata 0:06fdc09661c2 4
lemniskata 0:06fdc09661c2 5 Serial pc(USBTX, USBRX);
lemniskata 0:06fdc09661c2 6 osMutexId stdio_mutex;
lemniskata 0:06fdc09661c2 7 osMutexDef(stdio_mutex);
lemniskata 0:06fdc09661c2 8
lemniskata 0:06fdc09661c2 9 void Do(void const *data) {
lemniskata 0:06fdc09661c2 10
lemniskata 0:06fdc09661c2 11 int i=(int)data;
lemniskata 0:06fdc09661c2 12 while(1)
lemniskata 0:06fdc09661c2 13 {
lemniskata 0:06fdc09661c2 14 osMutexWait(stdio_mutex, osWaitForever);
lemniskata 0:06fdc09661c2 15 pc.printf("This is Thread #%d\n",i);
lemniskata 0:06fdc09661c2 16 osMutexRelease(stdio_mutex);
lemniskata 0:06fdc09661c2 17 wait(1);
lemniskata 0:06fdc09661c2 18 }
lemniskata 0:06fdc09661c2 19 }
lemniskata 0:06fdc09661c2 20
lemniskata 0:06fdc09661c2 21 int main() {
lemniskata 0:06fdc09661c2 22
lemniskata 1:458d82e37147 23 //Create an array of pointers to threads
lemniskata 0:06fdc09661c2 24 osThreadDef_t **my_threads=NULL;
lemniskata 1:458d82e37147 25
lemniskata 1:458d82e37147 26 //Initialize the first thread of the function Do()
lemniskata 0:06fdc09661c2 27 if(initThread(&my_threads,Do)==0)
lemniskata 0:06fdc09661c2 28 {
lemniskata 0:06fdc09661c2 29 pc.printf("Thread creation faile\n");
lemniskata 0:06fdc09661c2 30 return -1;
lemniskata 0:06fdc09661c2 31 }
lemniskata 0:06fdc09661c2 32 int i=1;
lemniskata 1:458d82e37147 33
lemniskata 1:458d82e37147 34 //Start the first thread
lemniskata 0:06fdc09661c2 35 osThreadCreate(my_threads[i-1],(void *) i);
lemniskata 0:06fdc09661c2 36 while(1) {
lemniskata 0:06fdc09661c2 37 i++;
lemniskata 0:06fdc09661c2 38 if(i<6)
lemniskata 0:06fdc09661c2 39 {
lemniskata 1:458d82e37147 40 //Reallocate memory for the next thread of the function Do()
lemniskata 0:06fdc09661c2 41 if(reAlloc(&my_threads,Do,i)==0)
lemniskata 0:06fdc09661c2 42 {
lemniskata 0:06fdc09661c2 43 pc.printf("Thread creation faile\n");
lemniskata 0:06fdc09661c2 44 return -1;
lemniskata 0:06fdc09661c2 45 }
lemniskata 1:458d82e37147 46 //Start the next thread
lemniskata 0:06fdc09661c2 47 osThreadCreate(my_threads[i-1],(void *) i);
lemniskata 0:06fdc09661c2 48 i++;
lemniskata 0:06fdc09661c2 49 }
lemniskata 0:06fdc09661c2 50 wait(0.2);
lemniskata 0:06fdc09661c2 51 }
lemniskata 0:06fdc09661c2 52 }