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 MAX_LEN (1 << 12)
- static int a, b, n;
- static int ans[MAX_LEN], len;
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;;
- 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 r = 0, x = pair[0]; x <= pair[1]; x++) {
- if (isPrime(x)) {
- if ((r = pthread_mutex_lock(&mtx)) != 0) {
- fprintf(stderr, "pthread_mutex_lock: %s\n", strerror(r));
- pthread_exit(NULL);
- }
- ans[len++] = x;
- if ((r = pthread_mutex_unlock(&mtx)) != 0) {
- fprintf(stderr, "pthread_mutex_unlock: %s\n", strerror(r));
- pthread_exit(NULL);
- }
- }
- }
- 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;
- pthread_mutex_init(&mtx, NULL);
- 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);
- pthread_mutex_destroy(&mtx);
- for (int i = 0; i < len; i++) {
- printf("%d ", ans[i]);
- }
- puts("");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement