我寫帶班,並行線程,互斥體,和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
在同一個堆棧上,它始終是同一個客戶。 –