-1
#include <pthread.h>
class Controller{
private:
int x;
int y;
public:
void Run();
int getX(){return x;};
int getY(){return y;};
int getXSpeed(){return xSpeed;};
int getYSpeed(){return ySpeed;};
void setLocation(int x2, int y2);
};
class AutomaticControl {
private:
int lastX;
int lastY;
Controller contr;
public:
AutomaticControl(Controller controller){
contr = controller;
}
void *Run(void);
static void *Run_helper(void *context){return ((AutomaticControl *)context)->Run();};
};
class Ballsearch {
private:
Controller contr;
public:
Ballsearch(Controller controller){
contr = controller;
};
void *Run();
static void *Run_helper(void *context){return ((Ballsearch *)context)->Run();};
};
在我的頭文件中提到了三個類:Controller AutomaticControl和Ballsearch。 現在我想創建兩個線程:這些是ballsearch.Run()和AutomaticControl.Run() 我創建它像下面的代碼。 這有效。 我使用了ballsearch funktion Run()中的控制器對象。這改變了x和y。 完成此操作後。還有一個線程處於活動狀態。 AutomaticControl Run()函數。 它也使用帶有getX()和getY()的控制器對象。 如果我在AutmaticControl中使用它,則沒有我期望的值。應該有ballsearch函數Run()中提到的值。 我該如何解決這個問題。用pthread創建兩個類創建並在cpp中相互訪問
這裏是CPP的完整代碼:
#include "Header.h"
using namespace std;
using namespace cv;
Controller contr1;
Ballsearch ballsearch(contr1);
AutomaticControl automaticcontr (contr1);
int main(int argc, char *argv[])
{
Controller contrl;
contrl.Run();
return 0;
}
void Controller::Run(){
pthread_t thread1;
pthread_t thread2;
pthread_create(&thread1,NULL,&Ballsearch::Run_helper,&ballsearch); // &ballsearch
pthread_create(&thread2,NULL,&AutomaticControl::Run_helper,&automaticcontr); //&automaticcontr
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
cout << "hello"<<endl;
}
void Controller::setLocation(int x2, int y2){
x = x2;
y = y2;
cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << endl;
cout << " x-Position: " << x <<" y -Position: " << y <<endl;
cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << endl;
}
void *Ballsearch::Run() {
cout << "ballsearch run" << endl;
contr.setLocation(20,30);
delay(3000);
}
void *AutomaticControl::Run() {
cout << "AutomaticControl run " << endl;
cout << "* Start Automatic Control *" << endl;
delay(1000);
lastX = contr.getX();
lastY = contr.getY();
cout << "-------------------------------------------------------------" << endl;
cout << " contr.getX() " << lastX << " contr.getY() " << lastY <<endl;
cout << "-------------------------------------------------------------" << endl;
}
https://stackoverflow.com/questions/5162549/how-to-access-the-same-data-using-threads – didierc
你不能測試它,因爲它是寫在視覺工作室。 我用它與覆盆子pi。 –
基本上,如果您有2個線程共享一條信息,您希望使用消息傳遞系統來通知每個線程數據已更改,並將該任務更新爲單個線程,或者共享該數據的訪問權限,以及使用互斥鎖來避免併發訪問。 – didierc