Eric
Eric

Reputation: 2705

pthread to run method of instances of a class in parallel

I have a Drone class, which is basically a pair of integers (x, y) for its location in a 2D cartesian plane, and prints its location while moving one step at once towards its destination (dest_x, dest_y).

I am doing this in

void * run(void);

method, which takes care of launching, moving, avoiding collision with other Drones.

The instances of Drones are stored in vector<Drone*> drones, which is a global variable.

When I initialized the Drones and ran run() sequentially, it printed out the result correctly.

For example,

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)

With

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

However, I wanted to run this in parallel, i.e. the Drones are moving concurrently, not one moving after another one finishes moving.

For this, I defined a helper class (pthread function from a class),

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

and tried passing it to pthread_create() like

pthread_t t[2];
for (int i = 0; i < 2; ++i) {
    pthread_create(&t[i], NULL, &Drone::run_helper, &drones[i]);
}

It runs without an error, but it does not print anything.

Does anyone see what is wrong in my code?

Thank you.


UPDATE:

I added

for (int i = 0; i < 2; ++i) {
    pthread_join(t[i], NULL);
}

to the end of the main function, and now it prints something, but a very strange one

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)

(I don't know why the drone id is so big. I initialized them with 0 and 1)

Should I join the thread?

If so, am I doing this wrong?(for example, should vector<Drone*> drones be a mutually exclusive resource?)

Upvotes: 0

Views: 528

Answers (1)

Nikolay K
Nikolay K

Reputation: 3850

You have error in this line

pthread_create(&t[i], NULL, &Drone::run_helper, &drones[i]);

You pass an address of the pointer (Drone**) and cast to pointer (Drone*). So change it to

pthread_create(&t[i], NULL, &Drone::run_helper, (void*)(drones[i]));

Upvotes: 1

Related Questions