i writing simple barbershop c/c++ project classes, pthreads, mutex, , conds running issue when create new customer object in loop:
void barbershop::simulate() { barber.start(); // start barber int custid = 1; while(1) { customer c(custid, *this); customers.push_back(c); c.start(); sleep(3); custid++; } }
void customer::start() { pthread_create(&thread, null, &customer::run, this); } void* customer::run(void *ptr) { customer* data = reinterpret_cast<customer*>(ptr); while(1) { printf("customer %d running...\n", data->id); sleep(3); } } when run program create threads fine whenever make new thread overwrite id's in other threads. output:
customer 1 running... 1 sec customer 1 running... 2 sec customer 1 running... 3 sec customer 2 running... 4 sec customer 2 running... 4 sec in loop say:
customer c(...); does not create new instance each loop iteration? why subsequent threads overwrite this?
update
class customer { private: pthread_t thread; pthread_cond_t cond; pthread_mutex_t mutex; static void* run(void *args); int id; barbershop *bs; public: customer(int _id, barbershop &_bs); ~customer(); void start(); }; customer::customer(int _id, barbershop &_bs) { id = _id; bs = &_bs; } update 2: pthread id's
customer 1 running...[3066383168] customer 2 running...[3057990464] customer 2 running...[3057990464] customer 3 running...[3049597760] customer 3 running...[3049597760] customer 3 running...[3049597760] customer 3 running...[3049597760] customer 4 running...[3049597760] customer 4 running...[3041205056] customer 4 running...[3041205056] customer 4 running...[3041205056] customer 5 running...[3041205056] customer 4 running...[3041205056] customer 5 running...[3032812352] customer 5 running...[3032812352]
in following segment
while(1) { customer c(custid, *this); customers.push_back(c); c.start(); sleep(3); custid++; } class instance c local scope of while loop. @ end of each iteration of loop, c destroyed.
so, when customers.push_back(c) copy of class taken (see (default) copy constructor) , added customers list. means when c.start() copy pushed onto vector has not been started, instance local loop. @ end of loop iteration of loop c destroyed. loop starts again , new c created.
edit: see martin james' , casey 's comments why behavior you're seeing happening
Comments
Post a Comment