Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <unistd.h>
- #include <thread>
- #include <vector>
- #include <signal.h>
- #include <semaphore.h>
- using namespace std;
- vector<thread*> th;
- static sem_t semaphore;
- void quit(int q)
- {
- cout << "End" << endl;
- exit(0);
- }
- void event(int index)
- {
- while(1)
- {
- static long count = 0;
- sem_wait(&semaphore);
- cout << "Thread:" << index << " Count:" << count << endl;
- count++;
- sem_post(&semaphore);
- usleep(10000);
- }
- }
- int main(int argc, char ** argv)
- {
- if(argc<2)
- {
- cerr << "Error: num-thread" << endl;
- exit(0);
- }
- int MAX_THREAD=atoi(argv[1]);
- signal(SIGINT,quit);
- if (sem_init(&semaphore, 0, 1) == -1)
- cerr << "Error: semaphore" << endl;
- for(int i = 0; i < MAX_THREAD; i++)
- {
- thread* t = new thread(event, i);
- th.push_back(t);
- }
- for(int i = 0; i < th.size(); i++)
- th[i]->join();
- return 0;
- }
Add Comment
Please, Sign In to add comment