1

I have a problem with pthread_create. I would like to make a thread to track the keyboard button, eg when I press the spacebar the program aborts the main loop.

Here is my code (create a thread):

void check_button_code(int *btn);
     // main 
    pthread_t trd;
    int btn = 1;
    pthread_create(&trd,NULL,check_button_code, &btn);

Action to break

void check_button_code(int *btn) {
    int a;
    printf("Press space to pause\n.");
    while (1) {
        a = getchar();
        if (a == 32) {
            *btn = 0;
            break;
        } else {
            printf("error %d\n", a);
        }
    }
    printf("zatrzymane\n");
}

Thank you in advance for your help.

dda
  • 6,030
  • 2
  • 25
  • 34

1 Answers1

1

First you have to wait for the thread to complete. Add to main, before returning,

 pthread_join(trd, NULL);

Otherwise, the main thread ends just after the thread is created. Your main() function should look like

int main() {
    pthread_t trd;
    int btn = 1;
    pthread_create(&trd,NULL,(void*)check_button_code, &btn);
    pthread_join(trd, NULL);
    return 0;
}

Then getchar() will not render the char until CR is pressed. So, to make the thread read a space, you have to enter a space, then press ENTER.

To deal with characters on the fly instead, see this answer, for instance. This way, space will be processed before waiting for enter to be pressed.

Déjà vu
  • 28,223
  • 6
  • 72
  • 100