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

创建线程

    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讲师

répondre à tous(3)
PHPzhong

不知道你的search_thread里是怎么操作vector的,不过感觉这里有点问题:

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

这个param有可能在线程启动之前就被释放或者重用,所以在search_thread里看到的可能不是你指定的那个param了。

伊谢尔伦

两个线程同时执行上面的代码?这指向的是同一个内存啊,

刘奇

要给多点代码才行,现在看不懂。。

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!