I have a producer/consumer concurrency problem that I'm working on. The problem is that I'm getting a segfa开发者_JAVA技巧ult thrown immediately after trying to create my first thread.
Relevant code:
customer is a struct declared as:
struct pr2_customer
{
pthread_t customer_id;
};
typedef struct pr2_customer customer;
customers is a c++ vector, declared like:
vector<customer> customers;
Create the thread:
for(int i = 0; i < ncustomers; i++)
{
cout<<"creating a customer\n";
pthread_create(&customers[i].customer_id, &attr, customerAction, (void*)i);
}
Output:
creating a customer
segfaultcustomerAction has a cout statement as it's first line which never gets executed, leading me to believe the thread is never created.
Any help is greatly appreciated.
What appears to me is that you haven't reserved any space in customers
. I think this is what you need:
vector<customer> customers(ncustomers);
Since youre using STL vectors, you should use the handy vector::iterator to iterate over your vector without caring about its size.
vector<customer>::iterator it;
And then iterate through it like this.
for (it = customers.begin(); it != customers.end(); it++)
You will need to allocate some room for your customers. You only have declared a vector of customers, but that vector is empty.
It is difficult to see why you are segfaulting as you seem to only have given a snippet. Where does your vector live and does it actually have any members yet? Where does ncustomers come from?
I'm not even sure why you are wrapping your pthread_id in a struct or are you intending to grow this class later?
精彩评论