anutka

Untitled

May 19th, 2021
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <sys/sysinfo.h>
  4. #include <stdlib.h>
  5. #include <limits.h>
  6. #include <sys/mman.h>
  7. #include <fcntl.h>
  8. #include <semaphore.h>
  9. #include <sys/stat.h>
  10.  
  11. typedef double (*function_t)(double);
  12.  
  13. double* pmap_process(function_t func, const double *in, size_t count);
  14.  
  15. void pmap_free(double *ptr, size_t count);
  16.  
  17. double* pmap_process(function_t func, const double *in, size_t count) {
  18.     int processes_num = get_nprocs();
  19.  
  20.     double* values = (double*) mmap(NULL, sizeof(double)*count, PROT_WRITE|PROT_READ, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
  21.  
  22.     sem_t* sem = (sem_t*) mmap(NULL, sizeof(sem_t), PROT_WRITE|PROT_READ, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
  23.  
  24.     for (size_t i = 0; i < count; i++) {
  25.         values[i] = in[i];
  26.     }
  27.  
  28.     sem_init(sem, 1, processes_num);
  29.  
  30.     pid_t pids[processes_num];
  31.  
  32.     for (size_t i = 0; i < processes_num; ++i) {
  33.         pids[i] = fork();
  34.    
  35.         if (pids[i] == 0) {
  36.             sem_wait(sem);
  37.             size_t from = i*count/processes_num;
  38.             size_t to = (i+1)*count/processes_num - 1;
  39.             if (i == processes_num) {
  40.                 to = count - 1;
  41.             }
  42.             for (from; from < to; from++) {
  43.                 values[from] = func(values[from]);
  44.             }
  45.  
  46.             sem_post(sem);
  47.             exit(0);
  48.         }
  49.       }
  50.       int sem_value = 0;
  51.       sem_getvalue(sem, &sem_value);
  52.       while(sem_value != processes_num) {
  53.           sem_getvalue(sem, &sem_value);
  54.       }
  55.       sem_destroy(sem);
  56.       return values;
  57. }
  58.  
  59. void pmap_free(double *ptr, size_t count) {
  60.     munmap(ptr, sizeof(double)*count);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment