c:c_threads:thread_class
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | |||
c:c_threads:thread_class [2021/03/05 17:12] – peter | c:c_threads:thread_class [2021/03/05 17:13] (current) – peter | ||
---|---|---|---|
Line 51: | Line 51: | ||
---- | ---- | ||
- | |||
- | <code cpp> | ||
- | #include < | ||
- | #include < | ||
- | #include < | ||
- | # | ||
- | |||
- | |||
- | // Wallet provides a service to add money in a Wallet. | ||
- | // | ||
- | // The same Wallet object is used between different threads, so a Lock is needed in the addMoney() method of the Wallet. | ||
- | // | ||
- | // Acquire lock before increment the money of Wallet and release lock before leaving that function. | ||
- | // | ||
- | // This member function, first acquires a lock then increments the internal money of wallet object by a specified count and then releases the lock. | ||
- | class Wallet | ||
- | { | ||
- | int mMoney; | ||
- | std::mutex mutex; | ||
- | | ||
- | public: | ||
- | Wallet() : | ||
- | int getMoney() | ||
- | void addMoney(int money) | ||
- | { | ||
- | mutex.lock(); | ||
- | for(int i = 0; i < money; ++i) | ||
- | { | ||
- | mMoney++; | ||
- | } | ||
- | mutex.unlock(); | ||
- | } | ||
- | }; | ||
- | |||
- | |||
- | // Five threads will share the same Wallet class object and each thread will add 1000 into the Wallet using the addMoney() member function in parallel. | ||
- | // | ||
- | // So, if initially the money in the wallet is 0, then then after completion of all the threads, the money in the Wallet should be 5000. | ||
- | // | ||
- | // Adding a mutex lock guarantees that Money in the Wallet will be 5000 at the end. | ||
- | int testMultithreadedWallet() | ||
- | { | ||
- | Wallet walletObject; | ||
- | std:: | ||
- | for(int i = 0; i < 5; ++i) { | ||
- | threads.push_back(std:: | ||
- | } | ||
- | for(int i = 0; i < threads.size() ; i++) | ||
- | { | ||
- | threads.at(i).join(); | ||
- | } | ||
- | return walletObject.getMoney(); | ||
- | } | ||
- | |||
- | |||
- | int main() | ||
- | { | ||
- | int val = 0; | ||
- | for(int k = 0; k < 1000; k++) | ||
- | { | ||
- | if((val = testMultithreadedWallet()) != 5000) | ||
- | { | ||
- | std::cout << "Error at count = "<< | ||
- | //break; | ||
- | } | ||
- | } | ||
- | |||
- | return 0; | ||
- | } | ||
- | </ | ||
- | |||
- | <WRAP info> | ||
- | **NOTE: | ||
- | </ | ||
c/c_threads/thread_class.1614964332.txt.gz · Last modified: 2021/03/05 17:12 by peter