0
#include <iostream>
#include <time.h>
#include <pthread.h>
using namespace std;

void*genFunc2(void*val)
{
    int i,j,k;
    for(i=0;i<(1<<15);i++)
    {
        clock_t t1=clock();
        for(j=0;j<(1<<20);j++)
        {
            for(k=0;k<(1<<10);k++)
            {

            }
        }
        clock_t t2=clock();
        cout<<"t1:"<<t1<<" t2:"<<t2<<" t2-t1:"<<(t2-t1)/CLOCKS_PER_SEC<<endl;
    }
}

int main()
{
    cout<<"begin"<<endl;
    pthread_t ntid1;pthread_t ntid2;pthread_t ntid3;pthread_t ntid4;
    pthread_create(&ntid1,NULL,genFunc2,NULL);
    pthread_create(&ntid2,NULL,genFunc2,NULL);
    pthread_create(&ntid3,NULL,genFunc2,NULL);
    pthread_create(&ntid4,NULL,genFunc2,NULL);
    pthread_join(ntid1,NULL);pthread_join(ntid2,NULL);
    pthread_join(ntid3,NULL);pthread_join(ntid4,NULL);
    return 0;
}

上記の例を示します。1 つのスレッドを作成するだけで、2 秒で時間を出力できます。ただし、4 つのスレッドを作成すると、各スレッドは 15 秒で結果を出力するだけです。なんで?

4

1 に答える 1