pthread以并行方式运行类实例的方法

pthread to run method of instances of a class in parallel

本文关键字:实例 方法 运行 并行 方式 pthread      更新时间:2023-10-16

我有一个Drone类,它基本上是一对整数(x, y),表示它在2D笛卡尔平面中的位置,并在向目标(dest_x, dest_y)一步移动的同时打印它的位置。

我在做这件事

void * run(void);

该方法负责发射、移动、避免与其他Drone s的碰撞。

Drones的实例存储在作为全局变量的vector<Drone*> drones中。

当我初始化Drone并按顺序运行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同时移动,而不是一个接一个地移动。

为此,我定义了一个助手类(类中的pthread函数),

static void* run_helper(void * context) {
    return ((Drone *)context)->run();
}

并尝试像一样将其传递给CCD_ 10

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);
}

到了主功能的末尾,现在它打印了一些东西,但一个非常奇怪的

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)

(我不知道为什么无人机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]));