Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ctime>
- #include <csignal>
- #include <iostream>
- #include <unistd.h>
- #include <pthread.h>
- #include <stdlib.h>
- using namespace std;
- struct tdata{
- int gen_num[100];
- }datam;
- struct tinfo{
- int n;
- int threadPair;
- };
- pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- bool cond;
- unsigned int dretvobrojac = 0;
- void *thread_a_action(void *arg){
- cond=false;
- pthread_mutex_lock(&mutex);
- srand (time(NULL)*dretvobrojac); // ako ne pomnozimo s counterom, svaki put daje iste brojeve
- int n=*((int*)arg);
- cout<<endl<<"Generirani brojevi: "<<endl;
- for (int i=0;i<n;i++){
- datam.gen_num[i]=rand()%99+1;
- cout<<"Num "<<i<<": "<<datam.gen_num[i]<<endl;
- }
- cond=true;
- pthread_mutex_unlock(&mutex);
- pthread_cond_signal(&condition); // probudi thread b
- }
- void *thread_b_action(void *arg){
- pthread_mutex_lock(&mutex); //mutex lock
- while(!cond) { // bez ovog uvjeta, thread se nekad zna zablokirati beskonacno
- pthread_cond_wait(&condition, &mutex); //cekaj uvjet
- }
- int n=*((int*)arg);
- int zbroj=0;
- for (int i=0;i<n;i++){
- zbroj=zbroj+datam.gen_num[i];
- }
- cout<<endl<<"Suma ="<<zbroj<<endl;
- pthread_mutex_unlock(&mutex);
- }
- int main (void)
- {
- int n,m;
- do{
- cout<<endl<<"Unesite broj random brojeva za funkciju prve dretve: "; cin>>n;
- }
- while(n>10 || n<1);
- cout << "Unesite koliko puta sve ponoviti: "; cin>>m;
- pthread_t threads[2];
- for(int i=0;i<m;i++) {
- dretvobrojac++;
- pthread_create(&threads[0],NULL,&thread_a_action,&n);
- pthread_create(&threads[1],NULL,&thread_b_action,&n);
- pthread_join(threads[0],0);
- usleep(10000); // 10 000 mikrosec, cisto da thread 2 ne stigne krenut prije nego ga thread 1 zakljuca
- pthread_join(threads[1],0);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement