I am trying to send vector as data to pthread. But when I am trying to print the thread id , its coming garbage value.
If I run this code with single thread, it works fine. But when I run it with 2 threads, its not working.
#include <iostream>
#include <pthread.h>
#include <vector>
using namespace std;
struct val {
int data;
int sData;
};
void *foo(void *a)
{
vector <val *>* b = (vector <val *>*)a;
for (val *it : *b) {
std::cout <<" thread " <<it->data;
std::cout <<" &&& " <<it->sData<<"-----------"<<endl;
}
}
int main()
{
pthread_t thr[2];
for (int j = 0; j < 2; j++) {
std::vector <val*> a;
for (int i = 0; i< 10; i++) {
val* t = new val();
t->data = j;
t->sData = j*10;
a.push_back(t);
}
pthread_create(&thr[j], NULL, &foo, &a);//creating threads
}
pthread_join(thr[0],NULL);
pthread_join(thr[1],NULL);
return 0;
}
expected output:
thread 0 &&& 0
....
....
thread 1 &&& 10
thread 1 &&& 10
....
....
Aucun commentaire:
Enregistrer un commentaire