Advertisement
cunha1

Untitled

Mar 20th, 2020
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. #include <ctime>
  2. #include <csignal>
  3. #include <iostream>
  4. #include <unistd.h>
  5. #include <pthread.h>
  6. #include <stdlib.h>
  7.  
  8. using namespace std;
  9.  
  10. struct tdata{
  11.     int gen_num[100];
  12. }datam;
  13.  
  14. struct tinfo{
  15.     int n;
  16.     int threadPair;
  17. };
  18.  
  19.  
  20.  
  21. pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
  22. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  23. bool cond;
  24. unsigned int dretvobrojac = 0;
  25.  
  26. void *thread_a_action(void *arg){
  27.     cond=false;
  28.     pthread_mutex_lock(&mutex);
  29.     srand (time(NULL)*dretvobrojac); // ako ne pomnozimo s counterom, svaki put daje iste brojeve
  30.     int n=*((int*)arg);
  31.     cout<<endl<<"Generirani brojevi: "<<endl;
  32.     for (int i=0;i<n;i++){
  33.         datam.gen_num[i]=rand()%99+1;
  34.         cout<<"Num "<<i<<": "<<datam.gen_num[i]<<endl;
  35.     }
  36.     cond=true;
  37.     pthread_mutex_unlock(&mutex);
  38.     pthread_cond_signal(&condition); // probudi thread b
  39. }
  40. void *thread_b_action(void *arg){
  41.     pthread_mutex_lock(&mutex); //mutex lock
  42.     while(!cond) { // bez ovog uvjeta, thread se nekad zna zablokirati beskonacno
  43.         pthread_cond_wait(&condition, &mutex); //cekaj uvjet
  44.     }
  45.     int n=*((int*)arg);
  46.     int zbroj=0;    
  47.     for (int i=0;i<n;i++){
  48.        zbroj=zbroj+datam.gen_num[i];
  49.     }
  50.     cout<<endl<<"Suma ="<<zbroj<<endl;
  51.     pthread_mutex_unlock(&mutex);
  52. }
  53.  
  54. int main (void)
  55. {
  56.     int n,m;
  57.     do{
  58.         cout<<endl<<"Unesite broj random brojeva za funkciju prve dretve: "; cin>>n;
  59.     }
  60.     while(n>10 || n<1);
  61.  
  62.     cout << "Unesite koliko puta sve ponoviti: "; cin>>m;
  63.     pthread_t threads[2];
  64.     for(int i=0;i<m;i++) {
  65.         dretvobrojac++;
  66.         pthread_create(&threads[0],NULL,&thread_a_action,&n);
  67.         pthread_create(&threads[1],NULL,&thread_b_action,&n);
  68.  
  69.         pthread_join(threads[0],0);
  70.         usleep(10000); // 10 000 mikrosec, cisto da thread 2 ne stigne krenut prije nego ga thread 1 zakljuca
  71.         pthread_join(threads[1],0);
  72.     }
  73.    return 0;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement