急求高手回答。用VC编程解决办法
急求高手回答。。。。。用VC编程
某工厂有两个生产车间和一个装配车间,两个生产车间分别生产A、B两种零件,装配车间的任务是把A、B两种零件组装成产品。两个生产车间每生产一个零件后都要分别把它们送到装配车间的货架F1、F2上,F1存放零件A,F2存放零件B,F1和F2的容量均为可以存放10个零件。装配工人每次从货架上取一个A零件和一个B零件然后组装成产品。请用多线程并发进行正确的管理
------解决方案--------------------
呵呵,闲着没事,简单写了个你看行么,
某工厂有两个生产车间和一个装配车间,两个生产车间分别生产A、B两种零件,装配车间的任务是把A、B两种零件组装成产品。两个生产车间每生产一个零件后都要分别把它们送到装配车间的货架F1、F2上,F1存放零件A,F2存放零件B,F1和F2的容量均为可以存放10个零件。装配工人每次从货架上取一个A零件和一个B零件然后组装成产品。请用多线程并发进行正确的管理
------解决方案--------------------
呵呵,闲着没事,简单写了个你看行么,
- C/C++ code
#include <iostream> #include <cstdio> #include <process.h> #include <windows.h> using namespace std; HANDLE hMutex1, hMutex2; class Product { public: int F1 ; int F2 ; Product() { F1 = 0; F2 = 0; hMutex1 = CreateMutex(NULL,FALSE,NULL); hMutex2 = CreateMutex(NULL,FALSE,NULL); //互斥量生成 start_Threads(); } friend void produce_A(void* p); friend void produce_B(void* p); friend void merge_AB(void* p); void start_Threads() { while(1) { _beginthread(produce_A, 0, (void*)this); _beginthread(produce_B, 0, (void*)this); _beginthread(merge_AB, 0, (void*)this); Sleep(1000); } } }; void produce_A(void* p) { Product* product = (Product*)p; //等待获得互斥对象的所有权 WaitForSingleObject(hMutex1,INFINITE); if(product->F1 < 10) { product->F1++; printf("Part A been produced, now total is %d .\n",product->F1); } Sleep(1000); //释放互斥对象的句柄 ReleaseMutex(hMutex1); } void produce_B(void* p) { Product* product = (Product*)p; //等待获得互斥对象的所有权 WaitForSingleObject(hMutex2,INFINITE); if(product->F2 < 10) { product->F2++; printf("Part B been produced, now total is %d .\n",product->F2); } Sleep(2000); //释放互斥对象的句柄 ReleaseMutex(hMutex2); } void merge_AB(void* p) { Product* product = (Product*)p; WaitForSingleObject(hMutex1,INFINITE); WaitForSingleObject(hMutex2,INFINITE); if(product->F1 > 0 && product->F2 > 0) { product->F1--; product->F2--; puts("a Finished Product!\n"); } Sleep(3000); ReleaseMutex(hMutex2); ReleaseMutex(hMutex1); } int main() { Product p; system("pause"); return 0; }
------解决方案--------------------