c++ - 多线程中vector push_back问题
PHP中文网
PHP中文网 2017-04-17 13:37:14
0
3
762

创建线程

    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中文网

认证高级PHP讲师

reply all(3)
PHPzhong

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.

伊谢尔伦

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

刘奇

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template