Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _GNU_SOURCE
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #include <sched.h>
- #include <stdbool.h>
- #include <unistd.h>
- #define LINE_SIZE (1 << 12)
- static int a, b, n;
- bool isPrime(int x) {
- if (x < 2) {
- return false;
- }
- if (x == 2) {
- return true;
- }
- for (int div = 2; div * div <= x; div++) {
- if (x % div == 0) {
- return false;
- }
- }
- return true;
- }
- void *routine(void *arg) {
- int *pair = (int*)arg;
- for (int x = pair[0]; x <= pair[1]; x++) {
- if (isPrime(x)) {
- printf("%d\n", x);
- }
- }
- return NULL;
- }
- int main(int argc, char *argv[]) {
- if (argc != 4) {
- fprintf(stderr, "WRONG USAGE!\n");
- exit(1);
- }
- a = atoi(argv[1]);
- b = atoi(argv[2]);
- n = atoi(argv[3]);
- if (!a || !b || !n) {
- fprintf(stderr, "WRONG Params!\n");
- exit(1);
- }
- cpu_set_t cpuset;
- CPU_ZERO(&cpuset);
- CPU_SET(0, &cpuset);
- CPU_SET(1, &cpuset);
- CPU_SET(2, &cpuset);
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);
- int nrElems = b - a + 1;
- if (nrElems % n) {
- fprintf(stderr, "WRONG values!\n");
- exit(1);
- }
- int intSize = (nrElems / n);
- pthread_t thread[n];
- int pairs[n][2];
- for (int i = 0; i < n; i++) {
- pairs[i][0] = a + i * intSize;
- pairs[i][1] = pairs[i][0] + intSize - 1;
- }
- int r = 0;
- for (int i = 0; i < n; i++) {
- if ((r = pthread_create(&thread[i], &attr, routine, pairs[i])) != 0) {
- fprintf(stderr, "pthread_create: %s\n", strerror(r));
- exit(1);
- }
- }
- for (int i = 0; i < n; i++) {
- if ((r = pthread_join(thread[i], NULL)) != 0) {
- fprintf(stderr, "pthread_join: %s\n", strerror(r));
- exit(1);
- }
- }
- pthread_attr_destroy(&attr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement