[英]std::thread communication issue
我正在構建一個多線程應用程序,但是我遇到了問題。 在應用程序中,我使用一個變量在線程之間進行通信,但是它不起作用。 因此,當您鍵入exit時 ,應用程序不會停止執行。
編碼:
//Program that controls an cadrocopter with the use of a
//Raspberry Pi, MPU 6050, an ultrasonic sensor, an HMC5883L and Arduino Leonardo
//to compile use "g++ ./quad.cpp -o ./quad -std=c++0x -pthread"
//
//Copyright Jan Hendrik Farr
#include <iostream> //used to input data
#include <string> //used to procces the userdata
#include <stdlib.h> //used to convert strings into floats
#include "./serial/serial.h" //used to communicate with the Arduino
#include <thread> //used to do multithreating
using namespace std;
//userinterface thread
void userInterface(int cmdPos1, float cmdPos[]){
string cmd = "";
cout << "************************" << endl;
cout << "* Quadrocopter control *" << endl;
cout << "* software *" << endl;
cout << "* *" << endl;
cout << "* version 0.1 *" << endl;
cout << "* *" << endl;
cout << "* Copyright J.H. Farr *" << endl;
cout << "************************" << endl << endl << endl;
while(cmdPos1 != 4){
cin >> cmd;
if(cmd == "move"){
cin >> cmdPos[0] >> cmdPos[1] >> cmdPos[2] >> cmdPos[3];
cmdPos1 = 1;
cout << endl << endl;
} else if(cmd == "move+"){
cin >> cmdPos[0] >> cmdPos[1] >> cmdPos[2] >> cmdPos[3];
cmdPos1 = 2;
cout << endl << endl;
} else if(cmd == "land"){
cmdPos1 = 3;
cout << endl << endl;
} else if(cmd == "exit"){
cmdPos1 = 4;
cout << endl;
} else {
cout << "invalid argument!!" << endl << endl;
}
}
}
//algorithm
void algorithm(float tele[], int cmdPos1, float cmdPos[]){
while(cmdPos1 != 4){
switch (cmdPos1){
case 2:
cout << "works!!";
break;
case 1:
break;
case 3:
break;
}
}
}
//gets telemetrydata from mpu
void gettelempu(float tele[], int cmdPos1){
while(cmdPos1 != 4){
}
}
//gets height from ultrasonic sensor
void getheight(float tele[], int cmdPos1){
while(cmdPos1 != 4){
}
}
//main function
int main(){
//telemetry data
float tele[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
//what to do
int cmdPos1 = 0;
//where to go
float cmdPos[4] = {0, 0, 0, 0};
thread t1(userInterface, cmdPos1, cmdPos);
thread t2(algorithm, tele, cmdPos1, cmdPos);
thread t3(gettelempu, tele, cmdPos1);
thread t4(getheight, tele, cmdPos1);
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
void gettelempu(float tele[], int cmdPos1)
該函數獲取自己的cmdPos
副本; 在調用它時,傳遞給它的值為0
,並且該函數永遠不會更改該值,因此循環永遠不會終止。 algorithm
和getheight
相同。
為了在一處更改此參數的值並具有其他功能,請參見更改功能必須通過引用獲取值:
void gettelempu(float tele[], int& cmdPos1)
創建線程時,您必須傳遞一個引用:
thread t3(gettelempu, tele, std::ref(cmdPos1));
但是,等等,還有更多! 不能保證在一個線程中對cmdPos1
所做的更改將對其他線程可見。 為了確保這一點,使其原子化。 在main
,變化
int cmdPos1 = 0;
至
std::atomic<int> cmdPos1 = 0;
並更改函數簽名以采用std::atomic<int>
而不是int
:
void gettelempu(float tele[], std::atomic<int>& cmdPos1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.