当前位置:   article > 正文

Linux信号量(简易版)

Linux信号量(简易版)

Sem.hpp(用于封装信号量):

  1. #include<iostream>
  2. #include<queue>
  3. #include<unistd.h>
  4. #include <semaphore.h>
  5. using namespace std;
  6. class Sem
  7. {
  8. public:
  9. Sem(int num)
  10. {
  11. sem_init(&_sem,0,num);
  12. }
  13. ~Sem()
  14. {
  15. sem_destroy(&_sem);
  16. }
  17. void V()
  18. {
  19. sem_post(&_sem);
  20. }
  21. void P()
  22. {
  23. sem_wait(&_sem);
  24. }
  25. private:
  26. sem_t _sem;
  27. };

 Task.hpp(封装任务队列):

  1. #include "sem.hpp"
  2. #include <iostream>
  3. #include <queue>
  4. #include <pthread.h>
  5. using namespace std;
  6. int num = 10;
  7. class Task
  8. {
  9. public:
  10. Task(): _space(num), _data(0)
  11. {
  12. pthread_mutex_init(&_mtx, nullptr);
  13. }
  14. void Push(int x)
  15. {
  16. _space.P(); // 生产者等待空间
  17. pthread_mutex_lock(&_mtx);
  18. q.push(x);
  19. cout << "生产了:" << x << endl;
  20. pthread_mutex_unlock(&_mtx);
  21. _data.V(); // 通知消费者数据已生产
  22. }
  23. void Pop()
  24. {
  25. _data.P(); // 消费者等待数据
  26. pthread_mutex_lock(&_mtx);
  27. cout << "消费了:" << q.front() << endl;
  28. q.pop();
  29. pthread_mutex_unlock(&_mtx);
  30. _space.V(); // 通知生产者空间已释放
  31. }
  32. private:
  33. Sem _space; // 空闲空间数量
  34. Sem _data; // 数据数量
  35. pthread_mutex_t _mtx;
  36. queue<int> q;
  37. };

 .cc:

  1. #include"Task.hpp"
  2. void* consumer(void* args)
  3. {
  4. Task* t = (Task*)args;
  5. while(1)
  6. {
  7. sleep(1);
  8. t->Pop();
  9. }
  10. return nullptr;
  11. }
  12. void* producer(void* args)
  13. {
  14. Task* t = (Task*)args;
  15. while(1)
  16. {
  17. t->Push(rand()%1000);
  18. }
  19. return nullptr;
  20. }
  21. int main()
  22. {
  23. srand(time(nullptr));
  24. Task* t = new Task;
  25. pthread_t Consumer[5];
  26. pthread_t Producer[5];
  27. for(int i = 0; i < 5; i++)
  28. {
  29. pthread_create(&Consumer[i], nullptr, consumer, (void*)t);
  30. pthread_create(&Producer[i], nullptr, producer, (void*)t);
  31. }
  32. for(int i = 0; i < 3; i++)
  33. {
  34. pthread_join(Consumer[i], nullptr);
  35. pthread_join(Producer[i], nullptr);
  36. }
  37. delete t;
  38. return 0;
  39. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/256191
推荐阅读
相关标签
  

闽ICP备14008679号