我写带班,并行线程,互斥体,和conds一个简单的理发店C/C++项目,但我遇到了一个问题,当我在一个循环中创建一个新的客户对象:并行线程循环覆盖指针
void BarberShop::simulate() {
barber.start(); // start the 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);
}
}
当我运行这个程序,它会创建线程不错,但每当我提出一个新的线程,将会改写ID在其他线程。输出:
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
在循环我说:
Customer c(...);
难道不是创建一个新的实例每次循环迭代?后续线程为什么会覆盖这个?
更新
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;
}
更新2:随着并行线程ID的
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]
你没有在你的类中存储客户ID作为一个静态成员变量是你吗?你能显示你的构造函数的代码吗? – Jimbo
@Jimbo已更新。 – user622469
在同一个堆栈上,它始终是同一个客户。 –