水曜日, 7月 17, 2013

Pthread

Ptheadとmutexのサンプルコードを書いてみた..

#include <iostream>
#include <sstream>
#include <pthread.h>
#include <cstdlib>
#include <unistd.h>
using namespace std;


class Account {
private:
 long _balance;
 pthread_mutex_t mutex;
public:
 explicit Account(long balance): _balance(balance) { pthread_mutex_init(&mutex,NULL); }
 virtual ~Account() { pthread_mutex_destroy(&mutex);}
 void Deposit(long val);
 long Withdraw(long val);
 friend ostream& operator << (ostream& os, const Account& acct);
};

inline ostream& operator << (ostream& os, const Account& acct) {
 os << acct._balance;
 return os;
}

typedef struct {
 Account* a;
 Account* b;
} Accts;

void Account::Deposit(long val) {

 pthread_mutex_lock(&mutex);
 _balance += val;
 pthread_mutex_unlock(&mutex);

}

long Account::Withdraw(long val) {

 pthread_mutex_lock(&mutex);
 _balance -= val;
 pthread_mutex_unlock(&mutex);
 return val;

}

void* PerformDrawer(void* param) {

 Accts* acct = static_cast<Accts*>(param);
 long l = 0;
 for( int i = 0;i < 50;i++ ) {
  cout << "[W" << i << "]:Draw money 300 from A and deposit the money into B.. " << endl;
  l = acct->a->Withdraw(300);
  acct->b->Deposit(l);
  cout << "current balances - A:" << *(acct->a) << ",B:" << *(acct->b) << endl;
  sleep(1);
 }
 
}

void* PerformDepositter(void* param) {

 Accts* acct = static_cast<Accts*>(param);
  for( int i = 0;i < 50;i++ ) {
  cout << "[D" << i << "]:Deposit money 500 into A.. " << endl;
  acct->a->Deposit(500);
  cout << "current balances - A:" << *(acct->a) << ",B:" << *(acct->b) << endl;
  sleep(1);
 }
}

void InitThreadAttr(pthread_attr_t* attr) {
 pthread_attr_init(attr);
 pthread_attr_setdetachstate(attr,PTHREAD_CREATE_JOINABLE);
}

int main() {

 pthread_t depositter;
 pthread_t withdrawer;
 void *status_depositter;
 void *status_withdrawer;
 
 Account A(4000);
 Account B(2000);
 Accts accts;
 accts.a = &A;
 accts.b = &B;
 pthread_attr_t attr;

 InitThreadAttr(&attr);
 
 pthread_create(&depositter, &attr,PerformDepositter,(void *)&accts);
 pthread_create(&withdrawer, &attr,PerformDrawer,(void *)&accts);
 pthread_attr_destroy(&attr);
 pthread_join(depositter, &status_depositter);
 pthread_join(withdrawer, &status_withdrawer);
 
 cout << "A:" << A << endl;
 cout << "B:" << B << endl;

 pthread_exit(NULL); 

}

実行結果は以下の通り
(途中略)
[D46]:Deposit money 500 into A..
current balances - A:13700,B:15800
[W46]:Draw money 300 from A and deposit the money into B..
current balances - A:13400,B:16100
[D47]:Deposit money 500 into A..
current balances - A:13900,B:16100
[W47]:Draw money 300 from A and deposit the money into B..
current balances - A:13600,B:16400
[D48]:Deposit money 500 into A..
current balances - A:14100,B:16400
[W48]:Draw money 300 from A and deposit the money into B..
current balances - A:13800,B:16700
[D49]:Deposit money 500 into A..
current balances - A:14300,B:16700
[W49]:Draw money 300 from A and deposit the money into B..
current balances - A:14000,B:17000
A:14000
B:17000

0 件のコメント: