c++ - pthread 并行运行类实例的方法

标签 c++ multithreading pthreads

我有一个 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/

相关文章:

c# - 如何处理使用(Py.GIL()) block pythonnet中的异常

c - 线程缓冲区 : how to prevent racing between clients and have client and server working on buffer simultaneously

c - 如何使用互斥量来同步此序列: (A or B)C (A or B) (A or B)C

C++:继承基类方法

c++ - 分配新chunk时如何控制 `std::deque`的chunk大小?

multithreading - 如何通过 QSqlQueryModel 进行异步查询?

C 中的并发 TCP 服务器调整其大小。

c++ - GUI 应用程序和单例/依赖注入(inject)

c++ - 将对象传递给方法 C++

java - java 集合的不可修改包装器是否使它们成为线程安全的?