c++ - Pthread Argument Passing -


i try create pthread , record time after running readin function when print time in main comes out incorrect value . i'm new threads , don't know if i'm passing arguments correct way. insight appreciated.

int main(int argc, char **argv){      int read;     pthread_t readerthread;      readwrite arglist;            arglist.filename= inputfile;     arglist.rval=(retval *) malloc(sizeof(struct retval));      read= pthread_create(&readerthread, null, readin,  (void *) &arglist );      cout << "total time reading: "<< (arglist.rval)->timeused << endl;  }  struct readwrite {     string filename;     retval * rval; } ;  struct retval{     int frequency;     double timeused; };  void * readin(void *arg) {  struct timeval now, later; gettimeofday(&now, null); readwrite* alist = static_cast<readwrite *>(arg); retval *rval = alist->rval; string filename = alist->filename;  ..... ..... .....  rval->frequency = dataset.size(); rval->timeused  = gettimeused(now, later);  cout << "correct time: " << dataset.size(); << endl;  pthread_exit(null);  }  **output**  total cpu time reading: -1.72723e-77 correct time: 22841 

you're not giving thread time run - printout in main can happen before thread function starts, or right in middle. have data race , undefined behavior.

you should wait thread finish before doing result in main. use pthread_join that.

(also c++11 has thread library <thread> should at, can avoid ugly casts it.)


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -