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

Dependencies:   Threads mbed-rtos mbed

main.cpp

Committer:
lemniskata
Date:
2013-06-29
Revision:
4:a25f2646a1bc
Parent:
3:681b2f7e1b41

File content as of revision 4:a25f2646a1bc:

#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);
   }
}

int main() {
    ThreadList* my_threads=NULL; //List of all Initialized threads
    ThreadList* thread; //pointer to the last created ThreadList element
     
    int max=5; 
    int i=1;
    while(1) 
    {
       
            //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 failed. \n");
              
            }
            else
            {
                //Start the thread and store the id
                thread->id=osThreadCreate(thread->thread,(void *) i);
                i++;
            }
        
        wait(0.2);
    }
}