有没有xdjm懂操作系统和c语言的阿?
小弟最近遇到一些代码,关于操作系统的,不时很懂。。请问有高人可以解答一下吗?
请问为什么第二个程序效率为什么比第一个高。。(找质数)
第一个
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX 100000
unsigned long int primes;
static void *primefunction() {
static unsigned long int i = 3, j, c = 0;
printf("2\n");
while (c < MAX) {
for (j = 0; j < c; j++)
if (i % primes == 0)
goto trynext;
// hier angekommen: i ist prim
primes = i;
printf("%ld\n", i);
trynext: i += 2;
}
return NULL;
}
int main (void) {
pthread_t prime_thread;
pthread_create( &prime_thread, NULL, &primefunction, NULL );
while (getchar() != '\n') ;
pthread_cancel(prime_thread);
exit(0);
}
第二个
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#define MAX 100000
unsigned long int primes;
int check_stdin () {
struct timeval timeout ;
fd_set readmask ;
int no_of_descriptors ;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
FD_ZERO (&readmask );
FD_SET ( fileno ( stdin ), &readmask );
no_of_descriptors = select ( FD_SETSIZE , &readmask , NULL , NULL , &timeout );
if ( no_of_descriptors >= 0)
return no_of_descriptors ;
else {
perror (" select error ");
exit ( EXIT_FAILURE );
}
}
int main(void) {
static unsigned long int i = 3, j, c = 0;
printf("2\n");
while (c < MAX) {
for (j = 0; j < c; j++) {
if (check_stdin() > 0 && getchar() == '\n')
return EXIT_SUCCESS;
if (i % primes == 0)
goto trynext;
}
// hier angekommen: i ist prim
primes = i;
printf("%ld\n", i);
trynext: i += 2;
}
return EXIT_SUCCESS;
}
非常感谢阿。。
页:
[1]