Mutithread variable share Topic is solved

ChibiOS public support forum for all topics not covered by a specific support forum.

Moderators: RoccoMarco, lbednarz, tfAteba

Post Reply
leon_titan
Posts: 24
Joined: Sun Jan 12, 2020 2:11 pm
Has thanked: 4 times

Mutithread variable share

Post by leon_titan »

Code: Select all


bool start = false;

// thread 1
static THD_WORKING_AREA(waThread1, 128);
static THD_FUNCTION(Thread1, arg) {
   while(true) {
      uprintf(": %u\n", start);
   }
}

// main thread
void somefunc() {
   start = true;
}



How to share variables between threads? I use the code above but the value of "start" is changed not as expected. When I change the start to true, the print is like:

Code: Select all

:1
:1
:1
:1
:0
:0
:0
:0
...


Why and how to do that correct?
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Mutithread variable share

Post by Giovanni »

Hi,

Make the variable "volatile" or the compiled will optimize it out.

Giovanni
leon_titan
Posts: 24
Joined: Sun Jan 12, 2020 2:11 pm
Has thanked: 4 times

Re: Mutithread variable share

Post by leon_titan »

Got it. Thx for reply.
leon_titan
Posts: 24
Joined: Sun Jan 12, 2020 2:11 pm
Has thanked: 4 times

Re: Mutithread variable share

Post by leon_titan »

after add volatile still got the same result :(
User avatar
Giovanni
Site Admin
Posts: 14895
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

Re: Mutithread variable share

Post by Giovanni »

I don't see enough code for an explanation. It is possible that thread is starving the others, there are no sleep functions called inside the loop.

Giovanni
Post Reply