0
私はN個のスレッドを作成し、そのスレッドで簡単な操作を行うのにかかる時間を計算しようとしています。スレッドのパフォーマンスをベンチマークする
私は変数が0
に初期化され、Nがスレッド数である値Nに達するまで待っています。こうすることで、すべてのスレッドがreturn文の前の部分(その関数の最後の行)までatleastで実行されるようにすることができます。
数字[0,N]
ここで、N is the number of threads we want to create
は何らかのランダムな順序で出力されるべきですが、意味を成していないものをいくつか印刷するべきです(アドレスがあるかもしれません)。いただきました!間違ったコードのこの作品で
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;
}
わからない:番号がランダムに印刷されていない理由を私の質問はここにコード
0からN
にあります。すべてのポインタ?
あなたの質問がありますか? – immibis
質問が更新されました – listen
複数のスレッドで非共有、非アトミック、非読み取り専用の共有オブジェクトへのアクセスは、未定義の動作です。 – EOF