【发布时间】:2013-07-19 16:22:42
【问题描述】:
我正在编写一个带有类、pthread、互斥锁和 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]
【问题讨论】:
-
您没有将客户 ID 作为静态成员变量存储在您的类中,是吗?你能显示你的构造函数的代码吗?
-
始终是同一个客户,在同一个地方,在同一个堆栈上。
-
复制或移动
pthread_mutex_t不是定义的行为。您应该禁用Customer的复制构造和分配 - 这当然意味着您不能将它们放在vector中。请改用vector<Customer*>。 -
@Martin James...呵呵!是的好地方。 +1
-
标签: c++ multithreading pthreads