我有一个 Drone
类,它基本上是一对整数 (x, y)
获取其在二维笛卡尔平面中的位置,并打印其位置,同时向目的地一次移动一步 (dest_x, dest_y)
.
我在做这个
void * run(void);
方法,负责发射、移动、避免与其他碰撞 Drone
Drone
的实例s 存储在 vector<Drone*> drones
中, 这是一个全局变量。
当我初始化 Drone
s 并运行 run()
依次正确打印出结果。
例如,
location: (0, 0)
.
.
location: (5, 5)
Warning: drone 1 and 0may collide. Running collision avoidance.
.
.
location: (15, 22)
location: (15, 23)
drone 0 successfully served its delivery request.
returning to the control center...
location: (14, 22)
location: (13, 21)
.
.
location: (0, 0)
与
Drone* d = new Drone(0);
d->set_loc(0, 0);
d->set_dest(15, 23);
drones.push_back(d);
.
.
drones[0]->run();
drones[1]->run();
但是,我想并行运行它,即 Drone
s 在同时移动,而不是一个移动一个接一个移动完成。
为此,我定义了一个辅助类(pthread function from a class),
static void* run_helper(void * context) {
return ((Drone *)context)->run();
}
并尝试将其传递给 pthread_create()
喜欢
pthread_t t[2];
for (int i = 0; i < 2; ++i) {
pthread_create(&t[i], NULL, &Drone::run_helper, &drones[i]);
}
它运行没有错误,但它不打印任何东西。
有人看到我的代码有什么问题吗?
谢谢。
更新:
我加了
for (int i = 0; i < 2; ++i) {
pthread_join(t[i], NULL);
}
到 main 函数的末尾,现在它打印了一些东西,但是一个非常奇怪的东西
Warning: drone drone_id: 82002080 location: ( and 08200272, may collide. Running collision avoidance.8200271)
drone_id: 8200208 location: (0, 8200270)
Warning: drone 0 and 8200270may collide. Running collision avoidance.
Segmentation fault (core dumped)
(不知道为什么drone id这么大,我用0和1初始化了)
我应该加入话题吗?
如果是这样,我做错了吗?(例如,vector<Drone*> drones
应该是互斥资源吗?)
最佳答案
你在这行有错误
pthread_create(&t[i], NULL, &Drone::run_helper, &drones[i]);
您传递指针的地址 (Drone**
) 并转换为指针 (Drone*
)。所以改成
pthread_create(&t[i], NULL, &Drone::run_helper, (void*)(drones[i]));
关于c++ - pthread 并行运行类实例的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26569998/