I have 3 thread
1) main thread with a while loop and 1 scanf function for choise job
2) a thread that read and writes on serial port
3) a thread for the speech operations
the program get the user choise with scanf function, set a global byte variable, and speech some words with the audio system, in the thread.
My problem is that, if I press the key for the choise and, immediately, press the return key, the global var is set but the job is not done. If I press the choise key, wait some time, not more 2 second, and press the return key, the job is done.
Code example:
while(1)
{
printf("Options:\n1) Pos\n2) Bec\n3) Rol\n4)" Impost. pos. iniz.\n5) Exit\nChoise:");
scanf(" %c",&job_choise);
if(job_choise == '1') JOB_TO_DO_THREAD_SPEACH = TELL_US_POSITION;
if(job_choise == '2') JOB_TO_DO_THREAD_SPEACH = TELL_US_PITCH;
if(job_choise == '3') JOB_TO_DO_THREAD_SPEACH = TELL_US_ROLL;
if(job_choise == '4') JOB_TO_DO_THREAD_SPEACH = SET_START_POSITION;
if(job_choise == '5')
{
JOB_TO_DO_THREAD_SPEACH = EXIT_FROM_PROGRAM;
JOB_TO_DO_THREAD_CMPS09 = EXIT_FROM_PROGRAM;
break;
}
}
---------------------
Is it normal?
It seems that you are writing to the global byte variable JOB_TO_DO_THREAD_SPEACH accessed by other 2 threads in the while loop without synchronization, which leads to undefined result.
@ sohguanh: yes, scanf is thread-safe.
@Robertlzw: true, I write in a gloval var, JOB_TO_DO_THREAD_SPEACH, accdessed by other 2 threads. But it is an 'one byte variable'. I think that writing a byte variable is an atomic operation. I wrong?
Thank