Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #include <semaphore.h>
- #include <pthread.h>
- #include <unistd.h>
- #define N 3
- using namespace std;
- pthread_t m_counter[N];
- pthread_t m_monitor;
- pthread_t m_collector;
- //sem_t read_sem; //forces mutual exclusion on read
- sem_t write_sem; //forces mutual exclusion on writes
- int messages_cnt = 0;
- void* counter_update_count(void* counter_index)
- {
- sleep(rand()%100);
- int* x = (int*) counter_index;
- cout << "Counter thread [" << *x <<"] received a message" << endl;
- sem_wait(&write_sem);
- cout << "Counter thread[" << *x <<"] : waiting to write" << endl;
- messages_cnt++;
- cout << "Counter thread[" << *x <<"] : now adding to counter, counter value = " << messages_cnt << endl;
- sem_post(&write_sem);
- return 0;
- }
- void* mointor_update_count(void*)
- {
- cout << "Monitor thread waiting to read counter";
- sleep(rand()%100);
- sem_wait(&write_sem);
- cout << "Monitor thread reading a count of " << messages_cnt << endl;
- messages_cnt = 0;
- //cout << "Monitor thread waiting to write" << endl;
- sem_post(&write_sem);
- return 0;
- }
- int main()
- {
- sem_init(&write_sem, 0, 1);
- for(int i = 0; i < N; ++i)
- {
- pthread_create(&m_counter[i],NULL,counter_update_count,(void*)(&i));
- }
- pthread_create(&m_monitor, NULL,mointor_update_count, NULL);
- for(int i = 0; i < N; ++i)
- {
- pthread_join(m_counter[i],NULL);
- }
- pthread_join(m_monitor, NULL);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement