I am try to create a pthread and then record some time after running my readIn function but when I print the time in main it comes out as an incorrect value . I'm new to threads and I don't know if I'm passing the arguments the correct way. Any insight would be 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 for 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 for reading: -1.72723e-77
Correct time: 22841
You're not giving your thread any time to run - the printout in main can happen before your thread function even starts, or right in the middle. So you have a data race and undefined behavior.
You should wait for the thread to finish before doing anything with the result in main
. Use pthread_join
for that.
(Also C++11 has a thread library <thread>
which you should look at, you can avoid those ugly casts with it.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.