这是一个将除数10000计算为1000创建的最大线程数的程序。
我认为实时性变大了。
n_Threads是1000
thread.c
struct tms mytms;
clock_t t1, t2;
if( (t1 = times( &mytms )) == -1 )
{
perror( "times 1" );
exit( 1 );
}
for( int i = 0; i < n_Threads; i++ )
{
if( pthread_create( &tid[i], NULL, &thread_func, NULL ) != 0 ){
fprintf( stderr, "pthread_create error!\n" );
fprintf( stderr, "%s\n", strerror( errno ) );
exit( 1 );
}
}
for( int i = 0; i < n_Threads; i++ )
{
pthread_join( tid[i], NULL );
}
if( (t2 = times( &mytms )) == -1 )
{
perror( "times 2" );
exit( 1 );
}
fprintf( stdout, "%d 의 약 수 의 개 수 : %d \n", MAX_NUMBER, shared_Value );
printf( "Real time : %.5f sec\n", (double)(t2 - t1) / CLK_TCK );
printf( "User time : %.5f sec\n", (double)mytms.tms_utime / CLK_TCK );
printf( "System time : %.5f sec\n", (double)mytms.tms_stime / CLK_TCK );
void* thread_func( void* arg )
{
while(loopValue<=MAX_NUMBER){
pthread_mutex_lock( (&mutex) );
if( MAX_NUMBER % loopValue == 0 ) {
shared_Value++;
}
loopValue++;
pthread_mutex_unlock( (&mutex) );
}
return NULL;
}
结果
10000 number of proper divisor : 25
Real time : 0.40000 sec
User time : 0.09000 sec
System time : 0.59000 sec
为什么系统时间大于实时时间?
系统时间是您的程序在操作系统中花费的时间;与用户时间相反,用户时间是您的程序花费在运行直接代码(+库)上的时间。
您似乎发现创建和删除线程会花费很多系统时间。您可能还发现增加10000次所需的时间比创建和删除线程要少得多。这些都是很好的教训。
此外,取决于互斥量是否已正确初始化;在无效的互斥锁上执行互斥锁操作所需的时间非常少;或您花费大量时间在单个互斥锁上颠簸了1000个线程。为了弄清楚哪个,您可以检查这些函数的返回值。经常发光。
也许从较少数量的线程开始。对于像您这样的程序,拥有比CPU多的线程是没有任何收获的。并非所有程序都如此。一些线程周期性地等待I / O操作等;但是很少有理由证明1000个线程。