简体   繁体   中英

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

You have two thread t s, 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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM