views:

74

answers:

4

Hello all,

I have a producer/consumer concurrency problem that I'm working on. The problem is that I'm getting a segfault 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
segfault

customerAction 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.

+1  A: 

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);
AraK
Thanks. Resizing the vector made it (kind of) work. Now I just have to figure out why it's deadlocking.
prelic
@prelic: Since your usage of vector is not for speed (but for convenience). Use the at() method (instead of operator[]) to get a reference to the object. This checks that the index is valid before returning the reference.
Martin York
A: 

You will need to allocate some room for your customers. You only have declared a vector of customers, but that vector is empty.

rturrado
+1  A: 

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++)
Aphex
A: 

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?

CashCow