search

Home  >  Q&A  >  body text

c++ - 多线程中vector push_back问题

创建线程

    pthread_t threads[2];
    MinPath minpath[2];
    Path* path[2];
    for (int j = 0; j < 2; ++j) {
        path[j] = new Path();
        printf("In main: creating thread %d\n", j);
        searchParam param ;
        param.minpath = &minpath[j];
        pthread_create(&threads[j], NULL, search_thread, (void *)&param);
    }

Path构造函数

struct Path{
    vector<int>* nodes;
    Path();
};
Path::Path(){
    nodes = new vector<int>;
    nodes->resize(10);
}

注意
两个线程使用的是一个数组的两个元素最为参数

  vector<int>* nodes = path->nodes;
  nodes->push_back(4);

1.虽然说是多线程,但两个线程没有共享变量
2.偶尔出错
3.每次都是这里有错,是不是应该每次resize一下,我试了一下好像不行
4.出错函数调用栈信息如下:

PHP中文网PHP中文网2808 days ago774

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 13:39:14

    I don’t know how to operate vector in your search_thread, but I feel there is something wrong here:

    pthread_create(&threads[j], NULL, search_thread, (void *)&param);

    This param may be released or reused before the thread is started, so the param you see in search_thread may not be the param you specified.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:39:14

    Two threads execute the above code at the same time? This points to the same memory,

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:39:14

    You need more code, I can’t understand it now. .

    reply
    0
  • Cancelreply