6 years, 1 month ago.  This question has been closed. Reason: Off Topic

Bug or my fault? Cannot create thread object inside if condition.

I am trying to use if/else condition to selectively run threads. However, I found that any thread object created inside if/else will not run at all. For example, following code will not run at all. However, if I remove the if(1) condition, it runs properly. I would like to ask whether it is a bug of mbed or my fault on design.

The board is nxp LPC1768.

example code of thread inside a condition, the mbed will freeze

#include "mbed.h"
#include "rtos.h"

DigitalOut led(LED1);
DigitalOut led2(LED2);
int32_t flag1=0;
int32_t flag2=0;
void led_thread(void const *argument) {

    while (true) {
           
        led = !led;
        Thread::wait(1000);
    }
}


void led_thread2(void const *argument) {

    while (true) {
        led2 = !led2;
        Thread::wait(500);
    }
}

int main (void) {
    if (1)
    {
    Thread thread1(led_thread);
    Thread thread2(led_thread2);
    }
    
    while (true) 
    {
       
    
    }
}

However, following code is fine when put thread object outside of if condition.

example code of thread outside a condition, the mbed will flash led

#include "mbed.h"
#include "rtos.h"

DigitalOut led(LED1);
DigitalOut led2(LED2);
int32_t flag1=0;
int32_t flag2=0;
void led_thread(void const *argument) {

    while (true) {
           
            
        led = !led;
        Thread::wait(1000);
    }
}


void led_thread2(void const *argument) {

    while (true) {
        led2 = !led2;
        Thread::wait(500);
    }
}

int main (void) {
//    if (1)
//    {
    Thread thread1(led_thread);
    Thread thread2(led_thread2);
//    }
    
    while (true) 
    {
       
    
    }
}

1 Answer

6 years, 1 month ago.

Thats C(++) working as intended :).

A variable in C++ (and the Thread is one) which is made like that is only valid within the block it is made in, so in your case within the if statement: It is created properly (at least I assume it is), only afterwards it is directly destroyed.

Either make them outside the if statement, or use new. If you use new it is never destroyed, so you need to watch that you don't keep creating new threads when that is not intended! (Then you got a memory leak).

Something like this:

new Thread(led_thread);

And if you want you can make a global Thread pointer which you can use to keep track of this thread.

Accepted Answer

I see. Sorry for my rusty C++ skill.

posted by Jindong Liu 09 Dec 2014