ubuntu 下的C++多线程遇到的问题(2)--向线程传递参数

#include <iostream>
#include <cstdlib>
#include<pthread.h>
using namespace std;


#define NUM_THREADS 5

void* say_hello(void *args)
{
    int ii=*((int *)args);
    cout<<"Hello Runoob!线程id"<<ii<<endl;
    pthread_exit(NULL);
}
int main()
{
    pthread_t tids[NUM_THREADS];
    int indexes[NUM_THREADS];
    for(int i=0;i<NUM_THREADS;i++)
    {
        //cout<<"main()创建线程,"<<i<<endl;
        indexes[i]=i;
        int ret=pthread_create(&tids[i],NULL,say_hello,(void*)&i);
        if(ret !=0)
        {
            cout<<"pthread_cread error:error_code"<<ret<<endl;
            exit(-1);
        }
    }
    pthread_exit(NULL);
    //cout << "Hello World!" << endl;
    return 0;
}


创建的线程id总是有时候会一样,后来对照教程一个一个看过去,也没找到不同之处,百度之,但是关键词真不知道(也没找到合想的),继续找不同,发现在

int ret=pthread_create(&tids[i],NULL,say_hello,(void*)&i);
而教程里是(void *)&indexes[i].最后试了下,发现数组才能很好保存,让每个线程id不一样.


最后,再次百度之,发现一个很好的关键词:向多线程传递参数. 在一篇博客上找到解释:

"在用传递指针或传递引用的方式时,要注意参数的作用域问题,保证被调函数返回前:1)变量地址不变,变量值不变".那篇博客用vector保存局部变量,可惜因为是动态开辟内存的,因此需要提前分配内存就行





猜你喜欢

转载自blog.csdn.net/snailyww/article/details/77541199