piloop.c 1.32 KB
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>

int calcpi() {
    int r[2800 + 1];
    int i, k;
    int b, d;
    int c = 0;

    for (i = 0; i < 2800; i++) {
        r[i] = 2000;
    }

    for (k = 2800; k > 0; k -= 14) {
        d = 0;

        i = k;
        for (;;) {
            d += r[i] * 10000;
            b = 2 * i - 1;

            r[i] = d % b;
            d /= b;
            i--;
            if (i == 0) break;
            d *= i;
        }
        c = d % 10000;
    }

    return 0;
}

void * thread_main(void * ptr) {
	while (1 == 1) calcpi();
}

int main(int argc, char * * argv) {
	if(argc < 2) {
		printf("\nUsage: %s <n> <p>\n\nWhere\n<n> is the number of threads to run in parallell\n<p> is the priority (optional)\n\n", argv[0]);
		return 0;
	}
	int numT = atoi(argv[1]);
	printf("\nStarting %d threads calculating PI. Hit Cntrl-C to stop or send a kill signal\n",numT);
	pthread_t lastT;
	int prio = 0;
	if(argc == 3) {
		prio = atoi(argv[2]);
		errno = 0;
		int res = nice(prio);
		if(errno != 0) {
			printf("Setting nice %d failed (code %d), are you root?\n", prio, errno);
		} else {
			printf("Process nice value set to %d\n", res);
		}
	}
	for(int x=0; x < numT; x++) {
		pthread_create(&lastT, NULL, thread_main, NULL);
	}
	pthread_join(lastT, NULL);
	exit(0);
}