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

Dependencies:   Threads mbed-rtos mbed

Revision:
4:a25f2646a1bc
Parent:
3:681b2f7e1b41
--- a/main.cpp	Sat Jun 29 22:06:29 2013 +0000
+++ b/main.cpp	Sat Jun 29 23:00:27 2013 +0000
@@ -1,19 +1,37 @@
 #include "mbed.h"
 #include "Threads.h"
+/*
+Author: Ivan Shindev
+Date: 06/29/2013
 
+This program creates multiple thread instances of the same function
+Each thread prints its number and terminates after 5 prints
+A new thread of the same function is created only if less
+than 5 threats are currently non-inactive 
+
+Mbed RTOS does not support multiple thread instances of the same function 
+with dynamic memory 
+
+Start the program and watch the miracle :)
+*/
 
 Serial pc(USBTX, USBRX);
 osMutexId stdio_mutex;
 osMutexDef(stdio_mutex);
 
+
 void Do(void const *data) {
   
    int i=(int)data;
+   int exec=0;
    while(1)
    {
         osMutexWait(stdio_mutex, osWaitForever);
             pc.printf("This is Thread #%d\n",i);
         osMutexRelease(stdio_mutex);
+        exec++;
+        if(exec>=5) //end the thread after 10 executions 
+            break;
    wait(1);
    }
 }
@@ -22,22 +40,26 @@
     ThreadList* my_threads=NULL; //List of all Initialized threads
     ThreadList* thread; //pointer to the last created ThreadList element
      
-    int i=0; 
+    int max=5; 
+    int i=1;
     while(1) 
     {
-        //We want 6 instances of the Do() function to run in separate threads 
-        if(i<6)
-        {
-            //Initialize a thread 
-            if(initThread(&my_threads,Do,&thread)==0)
+       
+            //Initialize a thread.
+            //A new thread is created only if the list has free space or
+            // one of started threads has finishid 
+            if(initThread(&my_threads,Do,&thread,max)==0)
             {
-                pc.printf("Thread creation faile\n");
-                return -1;
+               // pc.printf("Thread creation failed. \n");
+              
             }
-            //Start the thread and store the id
-            thread->id=osThreadCreate(thread->thread,(void *) i);
-            i++;
-        }
+            else
+            {
+                //Start the thread and store the id
+                thread->id=osThreadCreate(thread->thread,(void *) i);
+                i++;
+            }
+        
         wait(0.2);
     }
 }