FreeRTOS – Deleting Tasks

Keywords: Embedded systems, ARM, FreeRTOS, STM32F4, Tasks, Task Deletion

Code Link: Tutorial Source Code Github – Keil

In the previous tutorials we showed how to create tasks, pass parameters to task, and how to change tasks priority on fly. It is highly recommended to go through those tutorials before proceeding further. In this tutorial we will show how to delete a task.

Sometime few functionalities are no more required in system at run time. For example, lets say an embedded controller connected to various sensors and runs separate Tasks to manage various sensors data. At some point a sensor gets damage. In such scenario, keeping the task running not only contributes to power consumption but also wasts CPU cycles to be used by other tasks for various operations. In this scenarios, to keep system isolated from damaged sensors, the respective controlling task is better to be deleted.

Note: When a task is deleted in freeRTOS (via respective API), in first step its entry is removed from all lists (ready, block, suspended etc.) but its Task Control Block (TCB) and the memory reserved for it at the time of Task creation is kept reserved. In 2nd step, when IDLE TASK is allowed to run, it free up the deleted tasks reserved memory.

A word about Idle Task:

The idle task is created automatically when the RTOS scheduler is started to ensure there is always at least one task that is able to run. It is created at the lowest possible priority to ensure it does not use any CPU time if there are higher priority application tasks in the ready state. The idle task is responsible for freeing memory allocated by RTOS to tasks that have been deleted [1]. The Idle task acts as a garbage collector that clean up deleted task memory. The idle task has no other active functions so can legitimately be starved of microcontroller time under all other conditions.

Delete Task API:

The following API is used to delete FreeRTOS Task.

void vTaskDelete( TaskHandle_t xTask );

/*
@Params:
	xTask: 	The handle of the task to be deleted. Passing NULL will cause the calling task to be deleted.
*/

Note: In freeRTOSConfig.h INCLUDE_vTaskDelete must be defined as 1 for this function to be available.

Note: Calling vTaskDelete(...) for a Task only performs the 1st step of deletion process (as mentioned earlier) i.e. removing Task entry from all Tasks lists and scheduling it for proper deletion via Idle Task. The task memory remains reserved until reclaimed by Idle Task, Figure-1.

Figure-1: FreeRTOS Task Deletion Process

Tutorial Scenario:

In this tutorial, we will create two freeRTOS Tasks (Task-1 and Task-2) with equal priorities. After 20 Task Switching iterations, Task-1 will be deleted leaving behind only Task-2 to run forever.

Let’s jump to programming. Following are the steps.

Steps:

1. First of all declare TaskHandle_t handler which will be used in vTaskDelete API for Task-1.

TaskHandle_t hTask1;

2. Next create two FreeRTOS Tasks of equal priorities. As we will delete Task-1 later on fly (see tutorial scenario) so we need to refer to Task-1 later in code. For this purpose we need a task handler. we have already declared a global TaskHandle_t handler in previous step. Here we will only pass its pointer xTaskCreate(...) API.

  const int task_1_Param = 1;
  const int task_2_Param = 2;

  xTaskCreate (vTask, "T1", 150, (void *)&task_1_Param, 1, &hTask1);

  xTaskCreate (vTask, "T2", 150, (void *)&task_2_Param, 1, NULL);

3. Define a counter variable to be used to count number of times tasks being switched.

int counter = 0;

4. Upon 20th iteration, delete Task-1 by passing it handle to xTaskDelete(...). At this point forward only Task-2 will run as Task-1 has already been deleted.

if (counter == 20) {      
  printf("Deleting Task-1....\n");
  flag = 1;
  vTaskDelete(hTask1);
}

Note: As we mentioned previously that xTaskDelete(...) only stages a task for deletion. The actual memory is reclaimed by Idle Task. So we have a check at the start of Task Function that checks whether Task-1 was deleted or not. If flag is set i.e. flag == 1, then the task will be delayed for 1-tick time so that idle task has time to run and reclaim Task-1 memory.

/*
   if flag is set, it means the Task-1 is deleted
   so give some time to idle task to reclaim memory
*/
if (flag == 1) {
   vTaskDelay(1);
   flag  = 0;
}

The complete code for Tasks Function (used by both Task-1 and Task-2) is given bellow.

void vTask(void * pvParams) {

  volatile unsigned int i = 0;
  const int * tParam = (const int *)pvParams;
 
  for (;;) {

    /*
      if flag is set, it means the Task-1 is deleted
      so give some time to idle task to reclaim memory
    */
    if (flag == 1) {
      vTaskDelay(1);
      flag  = 0;
    }
    
    printf("Task-%d Running.\n", *tParam);
 
    /*
      prevents useless counting and redeletion of deleted task on overflow.
    */
    
    if (counter <=20) {
      counter++;
    }
    
    if (counter == 20) {      
      printf("Deleting Task-1....\n");
      flag = 1;
      vTaskDelete(hTask1);
    }
    
    /*Dummy Delay - Lazy work */
    for (i =0; i < 500000; ++i);
  }
}

5. Start the Scheduler.

vTaskStartScheduler();

6. Finally Compile source code, connect STM32F4-Discovery board to PC and enter debug mode. Open printf serial window via View -> Serial Windows -> Debug (printf) Viewer. Run the Program, You will see Task execution messages as shown in bellow Video.

Note: We have routed printf messages to ST-Link debugger via ARM-ITM. There is a dedicated tutorial on how to redirect printf messages to debugger. Link to the tutorial is given bellow.

For complete source code refer to Github link given at the start of this tutorial.

Click the full screen button for more clear view.

References:

[1] – FreeRTOS Official Website



99 thoughts on “FreeRTOS – Deleting Tasks”

  • Greetings from Ohio! I’m bored to death at work so I decided to check out your site on my
    iphone during lunch break. I love the information you
    present here and can’t wait to take a look when I get home.
    I’m amazed at how fast your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, superb site!
    asmr 0mniartist

  • I must thank you for the efforts you have put in writing
    this blog. I’m hoping to view the same high-grade content from you
    in the future as well. In fact, your creative writing abilities has encouraged me to get my own, personal website now 😉 asmr 0mniartist

  • Hello there! I know this is somewhat off topic but I was wondering if
    you knew where I could find a captcha plugin for
    my comment form? I’m using the same blog platform as yours and I’m
    having difficulty finding one? Thanks a lot!

    asmr 0mniartist

  • Have you ever considered publishing an e-book or guest authoring on other websites?

    I have a blog based upon on the same information you discuss and would really like to have
    you share some stories/information. I know my subscribers would
    enjoy your work. If you are even remotely interested,
    feel free to shoot me an e mail. 0mniartist asmr

  • Hey there! This is kind of off topic but I need
    some help from an established blog. Is it very difficult to set up your own blog?
    I’m not very techincal but I can figure things out pretty quick.

    I’m thinking about creating my own but I’m not sure where to start.

    Do you have any points or suggestions? Appreciate it asmr 0mniartist

  • Great post. I was checking continuously this blog and I am impressed!
    Extremely helpful info specifically the last part 🙂 I
    care for such information much. I was looking for this particular information for a
    long time. Thank you and good luck.

  • I’m impressed, I have to admit. Rarely do I encounter a blog that’s equally educative and
    engaging, and let me tell you, you’ve hit the nail on the head.

    The problem is something that not enough people are speaking intelligently about.
    Now i’m very happy that I came across this during my hunt
    for something relating to this.

  • I’ve learn some just right stuff here. Certainly worth bookmarking for
    revisiting. I wonder how so much attempt you set to make such a
    magnificent informative site.

  • What’s up to every body, it’s my first pay a visit of this weblog;
    this webpage includes amazing and truly fine information in support
    of readers.

  • What i do not realize is if truth be told how you’re now not actually much more neatly-appreciated than you may be right now.
    You’re so intelligent. You recognize thus considerably in terms of this subject,
    produced me individually imagine it from so many various angles.
    Its like women and men don’t seem to be interested until it is something to
    do with Girl gaga! Your personal stuffs excellent.

    At all times deal with it up!

  • Howdy, i read your blog occasionally and i own a similar one and i
    was just curious if you get a lot of spam remarks?
    If so how do you prevent it, any plugin or anything you can recommend?
    I get so much lately it’s driving me mad so any help is very much
    appreciated.

  • This is very interesting, You are a very skilled blogger.

    I have joined your rss feed and look forward to seeking more of your fantastic post.
    Also, I have shared your site in my social networks!

  • scoliosis
    Excellent pieces. Keep writing such kind of info on your page.
    Im really impressed by it.
    Hi there, You’ve performed an excellent job. I’ll certainly digg it and in my opinion recommend
    to my friends. I am confident they’ll be benefited from this site.
    scoliosis

  • scoliosis
    of course like your web site but you need to test the
    spelling on several of your posts. A number of them are rife with spelling problems and I find it very
    troublesome to tell the reality on the other hand I will definitely come again again. scoliosis

  • free dating sites
    Hey I know this is off topic but I was wondering if you knew
    of any widgets I could add to my blog that automatically tweet
    my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
    Please let me know if you run into anything. I truly enjoy
    reading your blog and I look forward to your new updates.

    free dating sites https://785days.tumblr.com/

  • I was more than happy to discover this website.
    I need to to thank you for your time due to this wonderful read!!

    I definitely savored every bit of it and
    I have you saved to fav to see new stuff in your site.

  • Oh my goodness! Amazing article dude! Many
    thanks, However I am going through issues with your
    RSS. I don’t know why I can’t subscribe to it. Is there anybody else having similar RSS problems?

    Anyone who knows the answer can you kindly respond?
    Thanks!!

  • Yesterday, while I was at work, my cousin stole my iphone and tested to see if it can survive a 25 foot drop, just
    so she can be a youtube sensation. My iPad is now destroyed and she has 83 views.
    I know this is entirely off topic but I had to share
    it with someone!

  • Howdy! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly?
    My website looks weird when viewing from my iphone.
    I’m trying to find a template or plugin that might be able to correct this
    problem. If you have any suggestions, please share.
    Cheers!

  • I enjoy what you guys are up too. This type of clever work
    and exposure! Keep up the very good works guys I’ve included you guys to blogroll.

  • Wonderful beat ! I wish to apprentice at the same time as you
    amend your website, how can i subscribe for a weblog site?
    The account aided me a applicable deal. I had been tiny
    bit familiar of this your broadcast provided bright clear concept

  • When I originally left a comment I seem to have clicked the -Notify me when new
    comments are added- checkbox and now whenever a comment is added I receive 4 emails with the same comment.
    There has to be a way you can remove me from that service?
    Thanks!

  • What’s Going down i am new to this, I stumbled upon this I’ve discovered
    It positively helpful and it has aided me out loads.
    I hope to contribute & aid other users like its helped me.
    Good job.

  • Hey! This is my first comment here so I just wanted to
    give a quick shout out and tell you I genuinely enjoy reading your blog posts.

    Can you suggest any other blogs/websites/forums that go over the same topics?
    Thanks a lot!

  • When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove people from that service? Thank you!

  • Hey! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My website looks weird when browsing from my apple iphone. I’m trying to find a template or plugin that might be able to correct this issue. If you have any suggestions, please share. With thanks!

  • The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you could fix if you werent too busy looking for attention.

  • Youre so cool! I dont suppose Ive read anything like this before. So nice to find somebody with some original thoughts on this subject. realy thank you for starting this up. this website is something that is needed on the web, someone with a little originality. useful job for bringing something new to the internet!

  • When I originally commented I clicked the -Notify me when new comments are added- checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thanks!

  • Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

  • Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.

  • An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  • Howdy just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Safari. I’m not sure if this is a format issue or something to do with web browser compatibility but I figured I’d post to let you know. The layout look great though! Hope you get the problem fixed soon. Cheers

  • magnificent submit, very informative. I ponder why the opposite experts of this sector don’t realize this. You must continue your writing. I’m sure, you’ve a huge readers’ base already!

  • Im impressed, I have to say. Really hardly ever do I encounter a blog thats both educative and entertaining, and let me let you know, you have got hit the nail on the head. Your idea is outstanding; the issue is one thing that not sufficient persons are talking intelligently about. I am very blissful that I stumbled across this in my search for one thing referring to this.

  • I’m not sure why but this website is loading incredibly slow for me. Is anyone else having this issue or is it a problem on my end? I’ll check back later and see if the problem still exists.

  • hello there and thank you for your info Ive certainly picked up anything new from right here. I did however expertise several technical issues using this site, since I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but slow loading instances times will very frequently affect your placement in google and could damage your quality score if advertising and marketing with Adwords. Anyway Im adding this RSS to my email and can look out for a lot more of your respective fascinating content. Make sure you update this again soon..

  • Hello! I know this is kinda off topic nevertheless I’d figured I’d ask. Would you be interested in exchanging links or maybe guest authoring a blog article or vice-versa? My website goes over a lot of the same subjects as yours and I think we could greatly benefit from each other. If you happen to be interested feel free to shoot me an e-mail. I look forward to hearing from you! Excellent blog by the way!

  • Hi there! This is kind of off topic but I need some advice from an established blog. Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about setting up my own but I’m not sure where to begin. Do you have any tips or suggestions? Thanks

  • I know this if off topic but I’m looking into starting my own weblog and was curious what all is required to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very internet savvy so I’m not 100 positive. Any suggestions or advice would be greatly appreciated. Many thanks

  • Good day! This is kind of off topic but I need some guidance from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty fast. I’m thinking about making my own but I’m not sure where to begin. Do you have any points or suggestions? Thank you

  • Have you ever thought about including a little bit more than just your articles? I mean, what you say is valuable and everything. But imagine if you added some great photos or video clips to give your posts more, “pop”! Your content is excellent but with images and videos, this website could definitely be one of the most beneficial in its field. Terrific blog!

  • Great blog! Do you have any recommendations for aspiring writers? I’m planning to start my own blog soon but I’m a little lost on everything. Would you suggest starting with a free platform like WordPress or go for a paid option? There are so many choices out there that I’m totally confused .. Any ideas? Thanks!

  • I’ve been exploring for a little bit for any high-quality articles or blog posts
    on this kind of area . Exploring in Yahoo I at last
    stumbled upon this web site. Studying this information So
    i’m happy to express that I’ve an incredibly just right uncanny
    feeling I discovered just what I needed. I such a lot
    surely will make sure to don?t overlook this website and give it a glance regularly.

  • It’s a pity you don’t have a donate button! I’d without a doubt donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this website with my Facebook group. Talk soon!

  • I wanted to draft you a little bit of word to thank you as before for the stunning tips you’ve provided here. It is quite tremendously generous with you to give extensively just what a few individuals would have supplied as an electronic book in order to make some cash for their own end, specifically considering that you might have tried it in the event you considered necessary. Those concepts in addition acted as a good way to realize that many people have the same keenness much like mine to learn a good deal more in terms of this problem. I’m certain there are many more pleasurable times in the future for many who look into your website.

Leave a Reply

Your email address will not be published. Required fields are marked *