c++ - How to make every thread pass another parameter? -


i'm not 100% sure how explain this, it's best see in code.

#include <unistd.h> #include <iostream> #include <cstdlib> #include <ctime> #include <pthread.h> #define n 30  using namespace std;  int zajednickopolje[50][n];  void *generiraj(void * i){     for(int j=0;j<n;j++)         zajednickopolje[*((int*)i)][j]=rand()%50; }  void *racunaj(void * i){     int suma=0;     for(int j=0;j<n;j++)         suma=suma+zajednickopolje[*((int*)i)][j];     sleep(1);     cout<<"polje"<<*((int*)i)<<" suma = "<<suma<<endl;     sleep(1);     cout<<"polje"<<*((int*)i)<<" aritm_sredina = "<<float(suma)/n<<endl; }  int main(){     int m, i;    cin>>m;    pthread_t thr_id[m*2];      for(i=0;i<m;i++)    if (pthread_create(&thr_id[i], null, generiraj, &i) != 0) {       cout<<"greska pri stvaranju dretve!\n";       exit(1);    }      for(i=m;i<(2*m);i++)    if (pthread_create(&thr_id[i], null, racunaj, &i) != 0) {       cout<<"greska pri stvaranju dretve!\n";       exit(1);    }     for(int i=0;i<(2*m);i++)    pthread_join(thr_id[i], null);     return 0; } 

so, want in main function pass variable "i" functions "generiraj" , "racunaj", it's value m*2. understand why happen, not sure how solve it?

there many options, important thing not pass pointer same i threads. 1 option, create dynamic storage integer;

for(i=0;i<m;i++) {    if (pthread_create(&thr_id[i], null, generiraj, new int(i)) != 0) {       cout<<"greska pri stvaranju dretve!\n";       exit(1);    } }  void *generiraj(void * ptr){     int = *(int*)ptr;     delete   (int*)ptr;      for(int j=0;j<n;j++)         zajednickopolje[i][j]=rand()%50;      return null; } 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -