c++ - 带线程的后台函数c++

标签 c++ multithreading

这是我的代码:

#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);
    }
}

我需要“stayAwake”函数在后台一直运行,直到用户输入有效数字,然后它应该停止并在 for 循环完成后立即再次启动。这只要我想要它。 (= 直到 Ctrl-C)

但是程序只是中断了:

terminate called without an active exception

最佳答案

您有两个 thread t,第二个位于 while 循环的底部,并立即超出范围并在线程未完成的情况下死亡,从而触发错误。

这应该会为您提供您想要的行为,或者类似的行为。

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);
        }
    }
}

关于c++ - 带线程的后台函数c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30270123/

相关文章:

c++ - 传递给线程后保持引用存活

java - 简单的链表和队列同步

java - ArrayBlockingQueue 如何避免混洗数组元素?

c++ - 如何使用整数列表在 LLVM 中初始化整数数组?

c++ - 关于 C++ 套接字,为什么服务器总是返回相同的结果?

c - 线程不并行运行

c# - 使用 UI 进行后台工作

c++ - gst_parse_launch 没有从字符串到 gchar 的正确转换函数

c++ - 为什么隐藏符号仍然添加到 DSO

c++ - 杀死父进程时杀死所有子进程