2 years ago.

Previous data of Queue is overwritten.

I used NUCLEO F303RE and OS5.

I tried to use Queue, but previous Queue data was overwritten to most recent value.

main.cpp

#include "mbed.h"

Serial pc(USBTX, USBRX);
Thread thread1;
Queue<int, 10> queue;

void callback(){
	int i=0;
	while(1){
		queue.put(&i);
        pc.printf("put %d\n\r", i);
		i++;
		wait(1);
	}
}

int main(){
	thread1.start(callback);

	while(1){
		while(!queue.empty()){
			osEvent evt = queue.get();
			int *tmp = (int*)evt.value.p;
			pc.printf("get %d\n\r", *tmp);
		}
		wait(3);
	}
}

output

put 0
put 1
put 2
get 3
get 3
get 3
put 3
put 4
put 5
get 6
get 6
get 6
put 6
put 7
put 8
get 9
get 9
get 9
put 9
put 10
put 11
get 12
get 12
get 12

Please tell me what is wrong.

2 Answers

2 years ago.

Since you are only sending the address of variable i, it is possible your i++ is firing before the main wait loop executes. I think the context switch will happen at the next 10ms systick so you can imagine printf and i++ in callback finishing before the switch occurs. Malloc is often used for items going into the queue so you have a unique variable to put in the queue. Then the handler frees it. Using the rtos Mail mechanism solves this too where you basically have a pool of messages/variables that can be used. In this example you could also probably just move i++ in callback() after the wait and it would run in the expected order.

Also what Bill said. That check is used in all the mbed queue examples.

Accepted Answer

I used Mail and it was solved. Thank you very mach.

posted by yuki takezawa 06 Apr 2019
2 years ago.

Hi Shouldn't you have a test for the status of the queue? See this example here where they use the status flag. One of the conditions is that *nothing* is in the queue...

https://os.mbed.com/docs/mbed-os/v5.12/apis/queue.html#ad033ffca23a9800b6607f08cec807417

 while (true) {
        osEvent evt = queue.get();
        if (evt.status == osEventMessage) {
            message_t *message = (message_t*)evt.value.p;