我正在爲一個類的最終項目工作。這個項目是模仿多個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任何幫助,在裏面工作一個作家鎖解鎖。謝謝 –