SHARE
TWEET

Untitled

a guest May 24th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #define N_THREADS 5
  5. #define ELEM 1000
  6. #define SEARCH 200
  7. int part = 0;
  8. int data[ELEM];
  9. int result[ELEM];
  10. pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
  11.  
  12. /**
  13.  * Iterates an array with multithreading (each thread does 'SEARCH' times)
  14.  * @param arg
  15.  * @return
  16.  */
  17. void * calculate(void *arg) {
  18.     int thread_count = part++;
  19.     int i;
  20.     for (i = thread_count * SEARCH; i < (thread_count + 1) * SEARCH; i++) {
  21.         /* Insert code to analyze inside array */
  22.         pthread_mutex_lock(&mut);
  23.         result[i] = 2 * data[i] + 10;
  24.         pthread_mutex_unlock(&mut);
  25.     }
  26.     pthread_exit(NULL);
  27. }
  28.  
  29. /**
  30.  * Thread creator,
  31.  * @param n = number of threads to create
  32.  * @param thread_ids = array with pthread_t
  33.  * @param start_routine = function to use
  34.  * @param args = arguments to pass to threads
  35.  * @param size = size of these arguments
  36.  */
  37. void create_threads(int n, pthread_t thread_ids[n], void *(*start_routine)(void *), void* args, int size) {
  38.     for (int i = 0; i < n; i++) {
  39.         if (pthread_create(&thread_ids[i], NULL, start_routine, (args + (size * i)))) {
  40.             perror("Error creating thread.");
  41.         }
  42.     }
  43. }
  44.  
  45. /**
  46.  * Waits for all threads to finish (generally used in main)
  47.  * @param n = number of threads
  48.  * @param thread_ids = array of threads
  49.  */
  50. void join_threads(int n, pthread_t thread_ids[n]) {
  51.     for (int i = 0; i < n; i++) {
  52.         pthread_join(thread_ids[i], NULL);
  53.     }
  54. }
  55.  
  56. /**
  57.  * Initializes an array with random data (integers)
  58.  */
  59. void array_initializer() {
  60.     int i;
  61.     srand(time(NULL));
  62.     for (i = 0; i < ELEM; i++) {
  63.         data[i] = rand() % 100;
  64.     }
  65. }
  66.  
  67. int main() {
  68.     array_initializer();
  69.     int i;
  70.     for (i = 0; i < ELEM; i++) {
  71.         printf("Data[%d] : %d\n", i, data[i]);
  72.     }
  73.  
  74.     pthread_t thread_ids[N_THREADS];
  75.     create_threads(N_THREADS, thread_ids, calculate, NULL, 0);
  76.     join_threads(N_THREADS, thread_ids);
  77.     printf("\n\n");
  78.    
  79.     for (i = 0; i < ELEM; i++) {
  80.         printf("Result[%d] : %d\n", i, result[i]);
  81.  
  82.     }
  83.  
  84.     return 0;
  85. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top