Advertisement
cunha1

Untitled

Mar 5th, 2020
367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. #include <iostream>
  2. #include <unistd.h>
  3. #include <cstdlib>
  4. #include <pthread.h>
  5. #include <sys/types.h>
  6. #include <csignal>
  7.  
  8. using namespace std;
  9. int n;
  10. int c=0;
  11. pthread_mutex_t monitor;
  12. pthread_cond_t red;
  13.  
  14. void prekid(int sig){
  15.     pthread_mutex_destroy(&monitor);
  16.     pthread_cond_destroy(&red);
  17.     kill(getpid(),SIGKILL);
  18. }
  19.  
  20. void *dretva(void *x){
  21.     int tid = (*(int*)x);
  22.     int a;
  23.     pthread_mutex_lock(&monitor);
  24.     c++;
  25.     cout << "Dretva: " << tid << ", unesite broj: ";
  26.     cin >> a;
  27.     if (c<n){
  28.         pthread_cond_wait(&red, &monitor);
  29.     }
  30.     else{
  31.         pthread_cond_broadcast(&red);
  32.     }
  33.     pthread_mutex_unlock(&monitor);
  34.  
  35.     pthread_mutex_lock(&monitor);
  36.     cout << "Dretva: " << tid << ", unesen je broj: " << a << endl;
  37.     pthread_mutex_unlock(&monitor);
  38. }
  39.  
  40. int main(int argc, char** argv){
  41.     int j[n];
  42.     if (argc==2){
  43.         n=atoi(argv[1]);
  44.     }
  45.     else return (0);
  46.     pthread_t d[n];
  47.     pthread_mutex_init(&monitor, NULL);
  48.     pthread_cond_init(&red, NULL);
  49.     sigset(SIGINT,prekid);
  50.    
  51.     for (int i=0;i<n;i++){
  52.         j[i]=i+1;
  53.         pthread_create(&d[i], NULL, dretva, &j[i]);
  54.     }
  55.     for (int i=0;i<n;i++){
  56.         pthread_join(d[i],NULL);
  57.     }
  58.     pthread_mutex_destroy(&monitor);
  59.     pthread_cond_destroy(&red);
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement