prelic
prelic

Reputation: 4518

Segfault immediately after pthread creation

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.

Upvotes: 1

Views: 288

Answers (4)

CashCow
CashCow

Reputation: 31435

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?

Upvotes: 0

Aphex
Aphex

Reputation: 7490

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++)

Upvotes: 1

rturrado
rturrado

Reputation: 8054

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

Upvotes: 0

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

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);

Upvotes: 1

Related Questions