I would like to get a value from the user, i.e. setpoint for a variable, inside a while loop without blocking other tasks to perform. I am trying to use pthreads and my trial resulted in a failure. Even though I am utilizing pthread, the program is blocked by the scanf function.
This is how I create the pthread inside the main() function
uint16_t refAngle = 0;
char refAngleString[64];
int main(void)
{
pthread_t thread_id;
while(1) {
pthread_create(&thread_id, NULL, threadUserInput, NULL);
pthread_join(thread_id, NULL);
// Other functions were called below ...
}
}
Then I have the thread function named threadUserInput
void *threadUserInput(void* vargp)
{
scanf("%s", refAngleString);
refAngle = (uint16_t) atoi(refAngleString);
printf("Angle is: %d\n", refAngle);
return NULL;
}
Any help would be appreciated, thanks in advance.
threadUserInput()is missing the statement:(void)vargp;and the statement:return NULL;should be:pthread_exit( NULL );scanf("%s", refAngleString);This places no limit on the length of the word that the user is allowed to enter, which can result in a input buffer overflow which results in undefined behavior The format string needs a MAX CHARACTERS modifier that is 1 less than the length of the input buffer, because '%s' always appends a NUL byte to the input. Using the MAX CHARACTERS modifier avoids any possibility of a buffer overflow and avoids any possibility of undefined behaviorpthread_create(&thread_id, NULL, threadUserInput, NULL); while(1) { // Other functions were called below ... } pthread_join(thread_id, NULL);Then modifying the thread function to loop rather than the current single passpthread_mutexso no race conditions result in the thread inputting a variable while the main function is processing that variable