HPA_1_5 - 8BitsCoding/RobotMentor GitHub Wiki

한 데이터에 접근해서 데이터 관리를 보여주는데 이런식의 관리는 위험함.

아마 예제이니 이런식으로 만든듯?

#include <thread>
#include "Account.h"
using namespace std;

enum ThreadType {
	DEPOSITOR,
	WITHDRAWER
};

Account account(5000.00);

void threadProc ( ThreadType typeOfThread ) {

	while ( 1 ) {
	switch ( typeOfThread ) {
		case DEPOSITOR: {
			cout << "Depositor: Current balance is "
			     << account.getBalance() << endl;

			account.deposit( 2000.00 );

			cout << "Depositor: Account balance after deposit is "
			     << account.getBalance() << endl;
			this_thread::sleep_for( 1s );
}
break;

		case WITHDRAWER: {
			cout << "Withdrawer: Current balance is "
			     << account.getBalance() << endl;

			account.withdraw( 1000.00 );

			cout << "Withdrawer: Account balance after withdrawing is "
			     << account.getBalance() << endl;
			this_thread::sleep_for( 1s );
		}
		break;
	}
	}
}

int main( ) {
	thread depositor ( threadProc, ThreadType::DEPOSITOR );
	thread withdrawer ( threadProc, ThreadType::WITHDRAWER );

	depositor.join();
	withdrawer.join();

	return 0;
}
#include <iostream>
using namespace std;

class Account {
private:
			double balance;
public:
			Account( double );
			double getBalance( );
			void deposit ( double amount );
			void withdraw ( double amount ) ;
};
#include "Account.h"

Account::Account(double balance) {
	this->balance = balance;
}

double Account::getBalance() {
	return balance;
}

void Account::withdraw(double amount) {
	if ( balance < amount ) {
		cout << "Insufficient balance, withdraw denied." << endl;
		return;
	}

	balance = balance - amount;
}

void Account::deposit(double amount) {
	balance = balance + amount;
}
$ g++-7 Account.cpp main.cpp -std=c++17 -lpthread

이미지

⚠️ **GitHub.com Fallback** ⚠️