SHARE
TWEET

Untitled

a guest May 19th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <string.h>
  6.  
  7. int n=5;
  8.  
  9. int a[5][5];
  10.  
  11. int b[5][5];
  12.  
  13.  
  14. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  15.  
  16. void *work(void *context) {
  17.  
  18.     int number=(long)context;
  19.     printf("\nnumber is= %d\n",number);
  20.     for (int i=0;i<n;i++)
  21.         a[number][i]=a[number][i]+b[number][i];
  22.     printf("\n");
  23.     pthread_mutex_unlock(&mutex);
  24.     pthread_exit(NULL);
  25. }
  26.  
  27. int main(int argc, char *argv[]) {
  28.  
  29.     for (int i=0;i<n;i++)
  30.         for (int j=0;j<n;j++){
  31.             a[i][j]=rand()%11;
  32.         }
  33.     for (int i=0;i<n;i++) {
  34.         for (int j = 0; j < n; j++) {
  35.             printf("%d ", a[i][j]);
  36.         }
  37.         printf("\n");
  38.     }
  39.     printf("\n");
  40.     for (int i=0;i<n;i++)
  41.         for (int j=0;j<n;j++){
  42.             b[i][j]=rand()%10;
  43.         }
  44.     for (int i=0;i<n;i++) {
  45.         for (int j = 0; j < n; j++) {
  46.             printf("%d ", b[i][j]);
  47.         }
  48.         printf("\n");
  49.     }
  50.     printf("\n");
  51.     pthread_t th[n];
  52.     for (size_t i = 0; i <= n; i++) {
  53.         pthread_mutex_lock(&mutex);
  54.         pthread_create(&th[i], NULL, work, (void*) i);
  55.  
  56.     }
  57.     for (int i = 1; i < argc; i++) {
  58.         pthread_join(th[i], NULL);
  59.  
  60.     }
  61.     for (int i=0;i<n;i++) {
  62.         for (int j = 0; j < n; j++) {
  63.             printf("%d ", a[i][j]);
  64.         }
  65.         printf("\n");
  66.     }
  67.     return 0;
  68. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top