Upcoming maintenance
Dear Customers and Partners.
This website will be undergoing scheduled maintenance on June 14, 2023. Please be aware there may be disruption to the developer portal website and associated services during the scheduled maintenance period.
This upgrade is essential to ensure the continued performance, reliability, and security of Developer World.
We apologize for any inconvenience.
How to share flags in spresense?
-
Sorry for the frequent postings.
I recently implemented a multi-threaded program using shared flags without mutex and it did not work.
And when I created a simple multi-threaded program using shared flags to try it out, the shared flags were not shared and I was able to run it on my computer, indicating that it is a spresense specific problem.
Is it a problem with the way spresense handles memory that the flags are not shared?
If anyone can tell me, I would appreciate your advice.↓Here are the results of the run with SPRESENSE.
| Start first thread | First thread : share_var = 1 | Start secound thread | Secound thread : share_var = 2 Secound thread : finished (stopped...)
↓Here is the execution result with WSL2 (gcc compiler).
| Start first thread | First thread : share_var = 1 | Start secound thread | Secound thread : share_var = 2 Secound thread : finished First thread : share_var = 3 First thread : finished
↓This is the program that was executed.
#include <stdio.h> #include <time.h> #include <pthread.h> int flag_1 = 0; int flag_2 = 0; int share_var = 0; static void *first_thread(){ printf("| Start first thread |\n"); share_var += 1; printf("First thread : share_var = 1 \n"); flag_1=1; while(flag_2==0); flag_2=0; share_var += 1; printf("First thread : share_var = 3 \n"); printf("First thread : finished\n"); return NULL; } static void *secound_thread(){ printf("| Start secound thread |\n"); while(flag_1==0); flag_1=0; share_var += 1; printf("Secound thread : share_var = 2\n"); flag_2=1; printf("Secound thread : finished\n"); return NULL; } // Main function // int main(void){ int ret; pthread_t thread1, thread2; ret = pthread_create(&thread1, NULL, first_thread, NULL); if (ret != 0){ printf("ERROR: Failed to create new thread1.\n"); } ret = pthread_create(&thread2, NULL, secound_thread, NULL); if (ret != 0){ printf("ERROR: Failed to create new thread2.\n"); } ret = pthread_join(thread1, NULL); if (ret != 0){ printf("ERROR: Failed to join first thread. \n"); } ret = pthread_join(thread2, NULL); if (ret != 0){ printf("ERROR: Failed to join secound thread. \n"); } return 0; }
-
This works.
volatile int flag_1 = 0; volatile int flag_2 = 0; volatile int share_var = 0;
Maybe you had different compiler flags. Arduino optimizes for size as a default.
To my knowledge volatile prevents the compiler from optimizing out as the compiler does not see that you modify the variable from another thread and thinks it is useless and removes it.
-
@jens6151-0-1-1 Thanks for your suggestion, It worked with that program.