pthread以并行方式运行类实例的方法
pthread to run method of instances of a class in parallel
我有一个Drone
类,它基本上是一对整数(x, y)
,表示它在2D笛卡尔平面中的位置,并在向目标(dest_x, dest_y)
一步移动的同时打印它的位置。
我在做这件事
void * run(void);
该方法负责发射、移动、避免与其他Drone
s的碰撞。
Drone
s的实例存储在作为全局变量的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]));
相关文章:
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 初始化指向类实例的智能指针并访问其方法
- 如何在没有实例的情况下获取非静态方法的类型?
- 使用动态实例化的对象填充矢量的快速方法
- 检查类是否在方法中实例化
- 所有类实例方法的打印语句最后都在打印吗?
- 当对象为值时访问实例方法<map>
- CPU寄存器中返回的用户定义类型的C 对象.实例方法如何工作
- 是否可以在实例方法中使用带有"this"的重载运算符?
- 如何使用带有实例方法的C++11线程
- 将 boost::function 与实例方法一起使用
- 在 Visual Studio 2008 C++ Express 中评估实例方法
- 如何通过禁用名称篡改来PInvoke实例方法
- 将C++实例方法与C回调函数混合使用
- 在同一个c#或c++类中可以有静态方法和实例方法吗?
- 使用随机数生成器:多实例或单实例方法
- 对象切片,不需要额外的实例方法和变量
- 为什么子类的非重写实例方法中的"this"类型是父类型?
- 子类调用基类构造函数,然后使用子类Arduino c++中基类的实例方法