[英]benchmarking the performance of threads
I am experimenting stuff and trying to calculate the time taken to create N threads and doing some simple operation in the thread. 我正在尝试一些东西,并尝试计算创建N个线程并在该线程中执行一些简单操作所需的时间。
I have a variable initialized to 0
and waiting till it reaches the value N, where N is the number of threads. 我有一个变量初始化为
0
,一直等到它达到值N,其中N是线程数。 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). 这样,我可以确保所有线程至少执行完,直到return语句之前的那个部分(该函数的最后一行)。
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). 我猜想数字
[0,N]
其中N is the number of threads we want to create
应该以某种随机顺序输出,但是打印一些没有意义的东西(地址可能是)。 My question is why are the number not being printed in a random fashion from 0 to N 我的问题是为什么数字不是从0到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?
有指针吗?
POSIX标准非常清楚,对象可能无法在一个线程中被访问,而在另一个线程中或可能会被修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.