Protothreads: block of all threads

How to block execution of all threads when a specific thread has to run to completion

Sometimes when using protothreads it is necessary to execute a thread and wait for it to end, but while doing this maybe you want to block the execution of all other threads. This article will show you how to achieve this.

In a piece of software of software I had to write recently, I had the need to sometimes make sure that a thread/task is run from beginning to end. While this task runs, I did not want any other thread to execute code.

I turns out that it is quite simple, although, as with all threads, one just has to take care to avoid some pitfalls.

Suppose there is some task, for example a protothread called CAN_init, that needs to be called, but all other threads need to be blocked. My solution was to create a new macro as follow:

/**
 * Run a thread forever until it exists
 *
 * No further multitasking will be done until the thread exists
 *
 * \param thread The child protothread with arguments
 *
 * \hideinitializer
 */
#define PT_RUN_COMPLETE(thread) while(PT_SCHEDULE(thread));

For a lack of a better description I called the macro PT_RUN_COMPLETE. As you can probably see it is very simple: it just repeatedly schedules the thread in question in a local while loop, and it will only exit the while loop once the thread is done.

To use it is then really simple:

....
PT_RUN_COMPLETE(CAN_Init); // this thread will never go past this point,
// or schedule any other thread unless CAN_Init
// is done executing
....

I realize this is a very simple example, but it is useful nevertheless.

Just a few comments and notes:

  • CAN_Init should not depend on something (like a flag, or a resource from another thread) to execute, otherwise you could have a deadlock
  • In my case CAN_Init needed to call PT_LOCK_ACQUIRE to lock a resource and CAN_Init was scheduled from other places as well - that is why I made it a protothread. You should carefully consider when you have a similar situation whether it will not be easier to make CAN_Init just a normal function that can be called, instead of having to schedule it using protothreads. Calling a function that is not a protothread will in any way block the execution of all other threads until it returns.

So there you go. My apologies for the short entry today, but time is money and the business will not wait!

armand Tuesday 06 May 2014 - 06:21 am | | Default

No comments

(optional field)
(optional field)
Remember personal info?
Small print: All html tags except <b> and <i> will be removed from your comment. You can make links by just typing the url or mail-address.