1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| #include"BlockQueue.hpp" #include"Task.hpp"
using namespace ns_blockqueue; #include<cstdlib> #include<ctime>
using namespace ns_task;
void* consumer(void* args) { BlockQueue<Task>* bq=(BlockQueue<Task>*)args;
while(true) {
Task t; bq->Pop(&t); t();
} }
void* producer(void* args) { BlockQueue<Task>* bq=(BlockQueue<Task>*)args; std::string ops="+-*/%";
while(true) {
sleep(1); int x=rand()%20+1; int y=rand()%10+1; char op=ops[rand()%5]; Task t(x,y,op); std::cout<<"生产派发了一个任务"<<x<<op<<y<<"="<<"?"<<std::endl; bq->Push(t); } }
int main() { srand((long long)time(nullptr)); BlockQueue<Task>* bq=new BlockQueue<Task>(6); pthread_t c,p; pthread_t c1,c2,c3,c4; pthread_create(&c,nullptr,consumer,(void*)bq); pthread_create(&c1,nullptr,consumer,(void*)bq); pthread_create(&c2,nullptr,consumer,(void*)bq); pthread_create(&c3,nullptr,consumer,(void*)bq); pthread_create(&c4,nullptr,consumer,(void*)bq); pthread_create(&p,nullptr,producer,(void*)bq); pthread_join(c,nullptr); pthread_join(p,nullptr); delete bq; return 0; }
|