我正在为一个类的最终项目工作。这个项目是模仿多个atm的。这是我的程序已经运行。在我的main.cpp里面,我创建了线程,现在只有两个,稍后可能会更多,他们称之为Begin(那个rand()),如果客户要存款或提取,然后rand()他们的数量去使用并做5次。如何挂起单独的类函数中的所有其他线程C++
#include "ATM.h"
void main()
{
Begin test1;
test1.manager();
thread first(&Begin::atm, test1);
thread second(&Begin::atm, test1);
first.join();
second.join();
delete resbox::cashbox;
system("pause");
}
我无法弄清楚如何暂停Main.cpp的创建我的主题我的观察()函数中,像这样:
void watcher::observe()
{
float cash;
if (resbox::cashbox->gettotal() >= resbox::cashbox->getmax())
{
//suspend all other threads
cout << "Please empty cash box it is full! with $"<< resbox::cashbox->gettotal() << endl;
cout << "How much would like to withdraw?" << endl;
cin >> cash;
resbox::cashbox->cashwd(cash);
cout << "This is the amount in the reserve box now is $" << resbox::cashbox->gettotal() << endl;
//resume all other threads
}
if (resbox::cashbox->gettotal() <= 500)
{
//suspend all other threads
cout << "Please fill cashbox it is low, has $" << resbox::cashbox->gettotal() << endl;
cout << "How much would like to add?" << endl;
cin >> cash;
resbox::cashbox->cashdp(cash);
cout << "This is the amount in the reserve box now $" << resbox::cashbox->gettotal() << endl;
//resume all other threads
}
}
只要满足条件的if语句的一个我需要能够挂起除满足条件的当前线程之外的所有其他线程。然后在离开if语句之前完成数据并且观察者函数恢复所有其他线程。
我读到了从这里使用SuspendThread和ResumeThread的可能性,how to suspend thread。然而,我很难将在main.cpp中创建的线程传递给观察者函数,以便我可以调用这些函数。我想出了如何从cplusplus.com创建线程,我也注意到我可能会使用互斥锁,因为我从What is the best solution to pause and resume pthreads?
我在Microsoft Visual Studio 2015社区下使用C++。
这是我第一次处理线程。对于我更好的使用,将创建的线程传递给观察者函数,或者有另一个暂停/暂停然后恢复它们,我将如何执行?感谢您提供的任何建议/帮助。
当前如果我运行我的程序,并且其中一个条件由线程满足,另一个线程也将满足相同的条件,并且必须在线程继续之前输入两次要存入/退出的金额,直到每个线程都有共处理5个客户,共10个客户。
显然,我需要创建一个共享的互斥体,然后有一个读者锁定和解锁ATM功能里面,有oberver功能不完全知道如何与互斥appriciated任何帮助,在里面工作一个作家锁解锁。谢谢 –