[英]benchmarking the performance of threads
我正在嘗試一些東西,並嘗試計算創建N個線程並在該線程中執行一些簡單操作所需的時間。
我有一個變量初始化為0
,一直等到它達到值N,其中N是線程數。 這樣,我可以確保所有線程至少執行完,直到return語句之前的那個部分(該函數的最后一行)。
我猜想數字[0,N]
其中N is the number of threads we want to create
應該以某種隨機順序輸出,但是打印一些沒有意義的東西(地址可能是)。 我的問題是為什么數字不是從0到N隨機打印
代碼在這里:
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;
}
不確定這段代碼有什么問題。 有指針嗎?
POSIX標准非常清楚,對象可能無法在一個線程中被訪問,而在另一個線程中或可能會被修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.