我正在编写一个带有类、pthreads、互斥锁和 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:使用 pthread 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]