piloop.c 2.45 KB
/************************************************************************************************
* All code in this file is under the MS-RL License (https://opensource.org/licenses/MS-RL)      *
* By using the code in this file in any way, you agree to the above license terms.              *
* Copyright (C) LIGHTS IN LINE AB (https://www.lightsinline.se)                                 *
* Repository, Wiki, Issue tracker and more at https://git.lightsinline.se/lilchger/piloop       *
*                                                                                               *
* Author: Christian Gerdes (christian.gerdes@lightsinline.se)                                   *
* Contributors                                                                                  *
* LIGHTS IN LINE AB                                                                             *
* SWEDBANK AB                                                                                   *                                                                                 *
************************************************************************************************/

#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);
}