![](/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.