Reputation: 247
I am experimenting stuff and trying to calculate the time taken to create N threads and doing some simple operation in the thread.
I have a variable initialized to 0
and waiting till it reaches the value N, where N is the number of threads. That way, I can ensure that all the threads are done executing atleast till the part before the return statement(last line of that function).
I am guessing that numbers [0,N]
where N is the number of threads we want to create
should be output in some random order but printing some stuff that doesnt make sense(addresses, may be). My question is why are the number not being printed in a random fashion from 0 to N
Code here:
void* increment(void *);
int main(int argc , char *argv[])
{
if(argc != 2) {
cout<<"Please provide the number of threads to create" <<endl;
return -1;
}
int nthreads = atoi(argv[1]);
pthread_t thread_ids[nthreads];
int count = 0;
struct timeval timeStart, timeEnd;
gettimeofday(&timeStart, NULL);
int i = 0;
while(i < nthreads)
{
pthread_t thread_id;
if( pthread_create( &thread_ids[i] , NULL , increment , (void*) &count) < 0)
{
error("could not create thread");
return 1;
}
++i;
}
while(count < nthreads)
{
cout<<"Waiting !"<<endl;
//repeat
}
gettimeofday(&timeEnd, NULL);
for(i = 0; i < nthreads; i++)
pthread_join(thread_ids[i], NULL);
std::cout << "This piece of code took "
<< ((timeEnd.tv_sec - timeStart.tv_sec) * 1000000L + timeEnd.tv_usec - timeStart.tv_usec) << " us to execute."
<< std::endl;
return 0;
}
void* increment(void *i)
{
int *p = (int*)i;
cout<<*p<<endl<<std::flush;
fflush(stdout);
*p = *p + 1;
return 0;
}
Not sure whats wrong in this piece of code. Any pointers?
Upvotes: 0
Views: 149
Reputation: 182885
The POSIX standard is quite clear that an object may not be accessed in one thread while it is, or might be, modified in another.
Upvotes: 2