代码之家  ›  专栏  ›  技术社区  ›  prelic

pthread创建后立即出现Segfault

  •  1
  • prelic  · 技术社区  · 14 年前

    我正在处理一个生产者/消费者并发问题。问题是,在尝试创建第一个线程后,立即抛出segfault。

    struct pr2_customer
    {
        pthread_t customer_id;
    };
    typedef struct pr2_customer customer;
    

    客户是一个c++向量,声明如下:

    vector<customer> customers;
    

    创建线程:

    for(int i = 0; i < ncustomers; i++)
    {
        cout<<"creating a customer\n";
        pthread_create(&customers[i].customer_id, &attr, customerAction, (void*)i);
    }
    

    输出:

    创建客户

    customerAction有一个cout语句,因为它的第一行永远不会被执行,这使我相信线程从来没有被创建过。

    任何帮助都非常感谢。

    4 回复  |  直到 14 年前
        1
  •  1
  •   Khaled Alshaya    14 年前

    我觉得你没有在 customers . 我想这就是你需要的:

    vector<customer> customers(ncustomers);
    
        2
  •  1
  •   Aphex Bodhi Hu    14 年前

    因为您使用的是STL向量,所以应该使用方便的vector::iterator在向量上迭代,而不必关心向量的大小。

    vector<customer>::iterator it;
    

    然后像这样迭代。

    for (it = customers.begin(); it != customers.end(); it++)
    
        3
  •  0
  •   rturrado    14 年前

    您需要为您的客户分配一些房间。您只声明了一个客户向量,但该向量为空。

        4
  •  0
  •   CashCow    14 年前

    我甚至不知道为什么要将pthread_id包装成一个结构,或者打算以后扩展这个类?