![](/img/trans.png)
[英]Return a function while daemon thread is working in the background (c++)
[英]background function c++ with thread
这是我的代码:
#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
s,其中第二个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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.