Ivan Shindev / Mbed 2 deprecated MutliThread

Dependencies:   Threads mbed-rtos mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 #include "Threads.h"
00003 /*
00004 Author: Ivan Shindev
00005 Date: 06/29/2013
00006 
00007 This program creates multiple thread instances of the same function
00008 Each thread prints its number and terminates after 5 prints
00009 A new thread of the same function is created only if less
00010 than 5 threats are currently non-inactive 
00011 
00012 Mbed RTOS does not support multiple thread instances of the same function 
00013 with dynamic memory 
00014 
00015 Start the program and watch the miracle :)
00016 */
00017 
00018 Serial pc(USBTX, USBRX);
00019 osMutexId stdio_mutex;
00020 osMutexDef(stdio_mutex);
00021 
00022 
00023 void Do(void const *data) {
00024   
00025    int i=(int)data;
00026    int exec=0;
00027    while(1)
00028    {
00029         osMutexWait(stdio_mutex, osWaitForever);
00030             pc.printf("This is Thread #%d\n",i);
00031         osMutexRelease(stdio_mutex);
00032         exec++;
00033         if(exec>=5) //end the thread after 10 executions 
00034             break;
00035    wait(1);
00036    }
00037 }
00038 
00039 int main() {
00040     ThreadList* my_threads=NULL; //List of all Initialized threads
00041     ThreadList* thread; //pointer to the last created ThreadList element
00042      
00043     int max=5; 
00044     int i=1;
00045     while(1) 
00046     {
00047        
00048             //Initialize a thread.
00049             //A new thread is created only if the list has free space or
00050             // one of started threads has finishid 
00051             if(initThread(&my_threads,Do,&thread,max)==0)
00052             {
00053                // pc.printf("Thread creation failed. \n");
00054               
00055             }
00056             else
00057             {
00058                 //Start the thread and store the id
00059                 thread->id=osThreadCreate(thread->thread,(void *) i);
00060                 i++;
00061             }
00062         
00063         wait(0.2);
00064     }
00065 }