julianmueller
julianmueller

Reputation: 131

background function c++ with thread

here is my code:

#include <wiringPi.h>

#include <stdio.h>
#include <iostream>
#include <string>
#include <unistd.h>
#include <thread>

using namespace std;

bool running;
const int pin = 1; // Pin 18 = Pin 1 in WiringPi

void stayAwake() {
    while(running) {
        digitalWrite(pin, 1);
        usleep(1000);
        digitalWrite(pin, 0);
        usleep(1000);
    }
}

int main() {
    if (wiringPiSetup() == -1)
        return 1;

    pinMode(pin, OUTPUT);

    running = true;
    thread t(stayAwake);

    while(1) {
        int input = 0;
        cout << "put in a freq between 1000 and 2000:";
        while(input < 1000 || input > 2000) cin >> input;

        running = false;
        t.join();
        for(int i=0; i<=1000; i++) {
            digitalWrite(pin, 1);
            usleep(input);
            digitalWrite(pin, 0);
            usleep(1000);
        }

        running = true;
        thread t(stayAwake);
    }
}

I need the "stayAwake" function to run the whole time in the background, until the user enters a valid number, then it should stop and immediately start again, after the for-loop has finished. ANd this as long as I want it. (= until Ctrl-C)

But the program just breaks up with:

terminate called without an active exception

Upvotes: 0

Views: 3028

Answers (1)

user4581301
user4581301

Reputation: 33932

You have two thread ts, the second of which is at the bottom of the while loop and instantly goes out of scope and dies without the thread completing, triggering the error.

This should give you the behaviour you want, or something close.

int main() {
    if (wiringPiSetup() == -1) {
        return 1;
    }
    pinMode(pin, OUTPUT);

    while(1) {
        running = true;
        thread t(stayAwake);
        int input = 0;
        cout << "put in a freq between 1000 and 2000:";
        while(input < 1000 || input > 2000) cin >> input;

        running = false;
        t.join();
        for(int i=0; i<=1000; i++) {
            digitalWrite(pin, 1);
            usleep(input);
            digitalWrite(pin, 0);
            usleep(1000);
        }
    }
}

Upvotes: 1

Related Questions