nanxing_basic_signal_linklist.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #ifndef NANXING_BASIC_SIGNAL_LINKLIST_
  2. #define NANXING_BASIC_SIGNAL_LINKLIST_
  3. #include"nanxing_defalloc.h"
  4. #include<mutex>
  5. #include<deque>
  6. namespace nanxing{
  7. template<typename T>
  8. struct link_node
  9. {
  10. T* data;
  11. link_node<T>* next;
  12. link_node(T _data):data(_data),next(nullptr){}
  13. link_node<T>& operator=(link_node<T>& _data)
  14. {
  15. data=std::move(_data.data);
  16. return *this;
  17. }
  18. link_node(T&& _data):data(_data){}
  19. };
  20. template<typename T,typename Alloc=nanxing::allocator<link_node<T>>>
  21. class basic_signal_linklist //注意这个和list的区别,链表会返回值而不是引用,在某些地方我们需要std::move而不是仅仅获得一个引用
  22. {
  23. private:
  24. std::mutex t;
  25. using pointer=link_node<T>*;
  26. int size=0;
  27. pointer head=nullptr; //头节点指针
  28. pointer end =nullptr; //这个相当于钻规则的空子,end是晚于head初始化的
  29. Alloc Creator;
  30. public:
  31. explicit basic_signal_linklist(){}
  32. int push(T&& data)
  33. {
  34. pointer ptr=Creator.allocate(sizeof(link_node<T>));
  35. if(ptr==nullptr)
  36. {
  37. return -1;
  38. }
  39. //Creator.construct(ptr,std::move(data));
  40. ptr->data=new std::packaged_task<void()>(std::move(data));
  41. //(ptr->data)();
  42. ptr->next=nullptr;
  43. if(head==nullptr)
  44. {
  45. head=ptr;
  46. end=ptr;
  47. }
  48. else
  49. {
  50. end->next=ptr;
  51. end=end->next;
  52. }
  53. size++;
  54. ptr=nullptr;
  55. return 0;
  56. }
  57. int list_size()
  58. {
  59. return size;
  60. }
  61. pointer pop()
  62. {
  63. std::unique_lock<std::mutex> lk(t);
  64. if(size==0)
  65. {
  66. return nullptr;
  67. }
  68. pointer ptr=head;
  69. head=head->next;
  70. size--;
  71. if(size==0)
  72. {
  73. end=nullptr;
  74. }
  75. return ptr;
  76. }
  77. ~basic_signal_linklist()
  78. {
  79. while(head!=end)
  80. {
  81. pointer ptr=head;
  82. head=head->next;
  83. Creator.destory(ptr);
  84. }
  85. if(head==end&&head!=nullptr)
  86. {
  87. Creator.destory(head);
  88. }
  89. }
  90. };
  91. }
  92. #endif