Garbage Collection

塵も積もれば山

目次

Blog 利用状況

ニュース

C++とかC#とか数学ネタを投下していく予定です。

[その他のページ]
日々の四方山話を綴った日記出水の日記帳

書庫

日記カテゴリ

[C++]mutexいろいろ

これは16日目の Boost Advent Calendar 2011 の参加記事です。

マルチスレッドのプログラムを作る場合、切っても切れないのがmutexです。
同じリソースにアクセスする時はmutexのロックを使って、
複数のスレッドが同時にアクセスするのを制限しないといけません。

例えば、std::cout で文字列を出力するのはスレッドセーフではないので、
複数のスレッドから同時に呼び出すと、出力が混じり合うことがあります。
なので、こんな感じでmutexを使って排他にしなければなりません。

static boost::mutex dispmutex;
void Display(const std::string &fname, const std::string &str){
  boost::mutex::scoped_lock lk(dispmutex);
  std::cout << fname << ":" << str << std::endl;
} 

scoped_lockを使うことで、そのスコープの間だけロックを掛ける、ということができます。
途中でreturnやbreakなどでスコープを抜けた場合もロックを外してくれるので、
mutexのlock/unlockを使うよりは、scoped_lockを使うといいでしょう。

 

さて、預金管理システムを作ってみました。
残高照会、預け入れ、引き出しができます。
預け入れに上限チェックしていませんが、
私の預金が32bitの上限が超えそうなときまでには考えます。

なお、どの関数も1秒ほどの処理時間がかかるものとします。

class Yokin{
  boost::mutex access;
  int money;
public:
  Human(int money):money(money){}
  void Zandaka(){
    boost::scoped_lock lk(access);
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

  void Azukeire(int h){
    boost::scoped_lock lk(access);
    money += h;
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

  void Hikidashi(int h){
    boost::scoped_lock lk(access);
    if (h <= money){
      money -= h;
    }
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  }
}; 

これは無駄な部分があるので、高速化してみます。
Zandaka()は値を読み込んで表示しているだけですので、
Azukeire()やHikidashi()が動いていない間なら並列で走らせても問題なさそうです。

そこで、boost::mutexより細かくロックレベルを変えられるのがboost::shared_mutexです。
それを使って先ほどのクラスを書き換えてみます。

class Yokin{
  boost::shared_mutex access;
  int money;
public:
  Human(int money):money(money){}
  void Zandaka(){
    boost::shared_lock<boost::shared_mutex> read(access);
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

  void Azukeire(int h){
    boost::unique_lock<boost::shared_mutex> write(access);
    money += h;
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

  void Hikidashi(int h){
    boost::unique_lock<boost::shared_mutex> write(access);
    if (h <= money){
      money -= h;
    }
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  }
}; 

値を読むだけならshared_lockを使い並列に動くようにして、
値を書き換える場合はunique_lockを使って排他にします。
これで、残高照会中に別スレッドの残高照会が動くようになって高速化しました。

しかし、もうちょっと高速化の余地があります。
Hikidashi()を見てみると、お金が足りない時はデータを書き換えません。
つまり、お金があるときのみ、unique_lockをすればよいです。
それを踏まえて書き換えてみます。

  void Hikidashi(int h){
    boost::shared_lock<boost::shared_mutex> shared(access);
    if (h <= money){
     boost::unique_lock<boost::shared_mutex> unique(access);
      money -= h;
    }
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

更に高速化!…するどころか、返ってきません。
どうやら、デッドロックしているようです。

お金を減らすとき、unique_lockを通過するには
shared_lockを含め、すべてのロックが外れていることが条件です。
しかし、自分自身がshared_lockをかけています。

  void Hikidashi(int h){
    boost::shared_lock<boost::shared_mutex> shared(access);
    if (h <= money){
      shared.unlock();
     boost::unique_lock<boost::shared_mutex> unique(access);
      money -= h;
    }
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

スコープの途中でも、unlock関数を使うことで、ロックを外すことができます。
もう使わない!となったらすぐに開放したほうがいいでしょう。

こうして、デッドロックはなくなりましたが…残高がマイナス??
どうやら、if文を抜けた後、別のスレッドで値を書き換えられたようです。

ロックは一度確保したら使い終わるまで一瞬でも開放してはいけません。
今回はshared_lockのアンロック→unique_lockの間に一瞬ロックが外れていて
その間に別のスレッドが値を書き換えているわけです。

こういう、書き換えるかもしれないときに使うロックがupgrade_lockです。

  void Hikidashi(int h){
    boost::upgrade_lock<boost::shared_mutex> upgrade(access);
    if (h <= money){
      boost::upgrade_to_unique_lock<boost::shared_mutex> write(upgrade);
      money -= h;
    }
    Display(__FUNCTION__, boost::lexical_cast<std::string>(money));
  } 

upgrade_lockはshared_lockとは干渉しないので
引き出し額が足りないときはZandaka()とは並列して動きます。
引き出し額が足りているときは、upgrade_to_unique_lockを使ってunique_lockに切りかえ、
その時にshared_lockが解除されるまで待ちます。

まとめると以下のようになります。

shared_lock unique_lockがあるときにブロック
upgrade_lock upgrade_lock, unique_lockがあるときにブロック
unique_lockに変更可能
unique_lock shared_lock, upgade_lock, unique_lockがあるときにブロック

アクセスが集中するリソースではこれらのロックを適切に使っていきたいです。

以上、Boost Advent Calender 2011 16日目、shared_mutexの紹介でした。
明日の17日目は @egtra さんです。
よろしくお願いします。

投稿日時 : 2011年12月16日 0:38

Feedback

# I actually found this more entertianing than James Joyce. 2012/10/18 9:20 Antonio

I actually found this more entertianing than James Joyce.

# <url>http://www.lowestquoteforinsurance.com/|insurance quotes</url> 515801 <url>http://www.carinsurshopping.com/|car insurance</url> 441 2012/10/28 0:24 Sandy

<url>http://www.lowestquoteforinsurance.com/|insurance quotes</url> 515801 <url>http://www.carinsurshopping.com/|car insurance</url> 441

# I don't even know how I ended up here, but I thought this post was great. I do not know who you are but certainly you're going to a famous blogger if you are not already ; ) Cheers! 2019/05/12 9:08 I don't even know how I ended up here, but I thoug

I don't even know how I ended up here, but I thought this post was great.
I do not know who you are but certainly you're going to a famous
blogger if you are not already ;) Cheers!

# I relish, cause I discovered exactly what I was having a look for. You have ended my four day long hunt! God Bless you man. Have a great day. Bye 2019/08/25 1:35 I relish, cause I discovered exactly what I was ha

I relish, cause I discovered exactly what I was having a look
for. You have ended my four day long hunt! God
Bless you man. Have a great day. Bye

# NButYVcxqQg 2021/07/03 2:54 https://amzn.to/365xyVY

Maybe You Also Make All of these Mistakes With bag ?

# does erectile dysfunction cause infertility 2021/07/06 18:40 hydrochoriquine

hydro clore quinn https://plaquenilx.com/# what is hydroxychloride

# re: [C++]mutex???? 2021/07/11 8:12 hydroxychoriquine

chloroquinw https://chloroquineorigin.com/# hydroxychloroquine eye

# re: [C++]mutex???? 2021/07/17 6:30 hydroxychloroquine side effects heart

who makes chloroquine phosphate https://chloroquineorigin.com/# how to make hydroxychloroquine

# re: [C++]mutex???? 2021/07/26 17:03 hydroxichlorquine

chloroquine phosphate tablet https://chloroquineorigin.com/# dolquine

# It's remarkable to pay a visit this website and reading the views of all mates on the topic of this article, while I am also eager of getting experience. 2021/08/28 13:07 It's remarkable to pay a visit this website and re

It's remarkable to pay a visit this website and reading the views of all mates on the
topic of this article, while I am also eager of getting experience.

# It is not my first time to pay a quick visit this site, i am visiting this web page dailly and get good information from here daily. 2021/08/30 8:28 It is not my first time to pay a quick visit this

It is not my first time to pay a quick visit this site, i am visiting this
web page dailly and get good information from here daily.

# My brother suggested I would possibly like this web site. He was entirely right. This publish truly made my day. You cann't consider simply how much time I had spent for this information! Thanks! 2021/08/31 22:28 My brother suggested I would possibly like this we

My brother suggested I would possibly like this web site.
He was entirely right. This publish truly made my day.
You cann't consider simply how much time I had spent for this information! Thanks!

# We are a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable information to work on. You've done an impressive job and our whole community will be thankful to you. 2021/09/02 1:13 We are a group of volunteers and starting a new sc

We are a group of volunteers and starting
a new scheme in our community. Your web site provided us with
valuable information to work on. You've done an impressive job and
our whole community will be thankful to you.

# We are a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable information to work on. You've done an impressive job and our whole community will be thankful to you. 2021/09/02 1:14 We are a group of volunteers and starting a new sc

We are a group of volunteers and starting
a new scheme in our community. Your web site provided us with
valuable information to work on. You've done an impressive job and
our whole community will be thankful to you.

# We are a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable information to work on. You've done an impressive job and our whole community will be thankful to you. 2021/09/02 1:15 We are a group of volunteers and starting a new sc

We are a group of volunteers and starting
a new scheme in our community. Your web site provided us with
valuable information to work on. You've done an impressive job and
our whole community will be thankful to you.

# We are a group of volunteers and starting a new scheme in our community. Your web site provided us with valuable information to work on. You've done an impressive job and our whole community will be thankful to you. 2021/09/02 1:16 We are a group of volunteers and starting a new sc

We are a group of volunteers and starting
a new scheme in our community. Your web site provided us with
valuable information to work on. You've done an impressive job and
our whole community will be thankful to you.

# Hello to every body, it's my first visit of this web site; this web site carries remarkable and in fact fine stuff designed for visitors. 2021/09/03 9:59 Hello to every body, it's my first visit of this w

Hello to every body, it's my first visit of this web site; this web site carries remarkable and in fact fine stuff designed for visitors.

# It's a pity you don't have a donate button! I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with m 2021/09/04 20:37 It's a pity you don't have a donate button! I'd m

It's a pity you don't have a donate button!
I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and
adding your RSS feed to my Google account. I look forward to fresh updates and will share
this blog with my Facebook group. Chat soon!

# It's a pity you don't have a donate button! I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with m 2021/09/04 20:38 It's a pity you don't have a donate button! I'd m

It's a pity you don't have a donate button!
I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and
adding your RSS feed to my Google account. I look forward to fresh updates and will share
this blog with my Facebook group. Chat soon!

# It's a pity you don't have a donate button! I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with m 2021/09/04 20:39 It's a pity you don't have a donate button! I'd m

It's a pity you don't have a donate button!
I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and
adding your RSS feed to my Google account. I look forward to fresh updates and will share
this blog with my Facebook group. Chat soon!

# It's a pity you don't have a donate button! I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this blog with m 2021/09/04 20:40 It's a pity you don't have a donate button! I'd m

It's a pity you don't have a donate button!
I'd most certainly donate to this excellent blog! I suppose for now i'll settle for book-marking and
adding your RSS feed to my Google account. I look forward to fresh updates and will share
this blog with my Facebook group. Chat soon!

# Hi would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but I'm having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and sty 2021/09/05 8:54 Hi would you mind stating which blog platform you'

Hi would you mind stating which blog platform you're working with?
I'm going to start my own blog in the near future but I'm having
a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique.
P.S My apologies for being off-topic but I had to ask!

# Hi would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but I'm having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and sty 2021/09/05 8:55 Hi would you mind stating which blog platform you'

Hi would you mind stating which blog platform you're working with?
I'm going to start my own blog in the near future but I'm having
a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique.
P.S My apologies for being off-topic but I had to ask!

# Hi would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but I'm having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and sty 2021/09/05 8:56 Hi would you mind stating which blog platform you'

Hi would you mind stating which blog platform you're working with?
I'm going to start my own blog in the near future but I'm having
a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique.
P.S My apologies for being off-topic but I had to ask!

# Hi would you mind stating which blog platform you're working with? I'm going to start my own blog in the near future but I'm having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and sty 2021/09/05 8:57 Hi would you mind stating which blog platform you'

Hi would you mind stating which blog platform you're working with?
I'm going to start my own blog in the near future but I'm having
a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design and style seems different then most blogs and I'm looking for something unique.
P.S My apologies for being off-topic but I had to ask!

# I like it when folks come together and share views. Great blog, keep it up! 2021/10/26 20:40 I like it when folks come together and share views

I like it when folks come together and share views.
Great blog, keep it up!

# I like it when folks come together and share views. Great blog, keep it up! 2021/10/26 20:41 I like it when folks come together and share views

I like it when folks come together and share views.
Great blog, keep it up!

# Why people still use to read news papers when in this technological globe the whole thing is available on web? 2021/11/12 11:50 Why people still use to read news papers when in t

Why people still use to read news papers when in this technological globe the whole thing is available on web?

# I every time spent my half an hour to read this webpage's posts everyday along with a mug of coffee. 2021/12/19 17:03 I every time spent my half an hour to read this we

I every time spent my half an hour to read this webpage's posts everyday along with a mug of coffee.

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and aid others like you helped me. 2021/12/20 19:09 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful
& it helped me out a lot. I hope to give something back and
aid others like you helped me.

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and aid others like you helped me. 2021/12/20 19:09 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful
& it helped me out a lot. I hope to give something back and
aid others like you helped me.

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and aid others like you helped me. 2021/12/20 19:10 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful
& it helped me out a lot. I hope to give something back and
aid others like you helped me.

# Heya i'm for the first time here. I came across this board and I find It really useful & it helped me out a lot. I hope to give something back and aid others like you helped me. 2021/12/20 19:11 Heya i'm for the first time here. I came across th

Heya i'm for the first time here. I came across this board and I find It really useful
& it helped me out a lot. I hope to give something back and
aid others like you helped me.

# Hello i am kavin, its my first time to commenting anyplace, when i read this piece of writing i thought i could also create comment due to this brilliant piece of writing. 2022/01/01 23:03 Hello i am kavin, its my first time to commenting

Hello i am kavin, its my first time to commenting anyplace,
when i read this piece of writing i thought i could also create comment due to this brilliant piece of writing.

# Hello would you mind stating which blog platform you're working with? I'm planning to start my own blog soon but I'm having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design and style s 2022/01/10 22:57 Hello would you mind stating which blog platform y

Hello would you mind stating which blog platform you're working with?

I'm planning to start my own blog soon but I'm having a difficult time deciding
between BlogEngine/Wordpress/B2evolution and Drupal.

The reason I ask is because your design and style seems different then most blogs and I'm looking
for something unique. P.S My apologies for getting off-topic but I
had to ask!

# I am truly happy to read this weblog posts which contains plenty of useful information, thanks for providing these kinds of statistics. 2022/01/14 16:54 I am truly happy to read this weblog posts which c

I am truly happy to read this weblog posts which contains plenty of useful information, thanks for providing
these kinds of statistics.

# Great post but I was wondering if you could write a litte more on this topic? I'd be very thankful if you could elaborate a little bit further. Thanks! 2022/01/29 1:26 Great post but I was wondering if you could write

Great post but I was wondering if you could write a litte more on this topic?
I'd be very thankful if you could elaborate a little bit further.
Thanks!

# Great post but I was wondering if you could write a litte more on this topic? I'd be very thankful if you could elaborate a little bit further. Thanks! 2022/01/29 1:27 Great post but I was wondering if you could write

Great post but I was wondering if you could write a litte more on this topic?
I'd be very thankful if you could elaborate a little bit further.
Thanks!

# Great post but I was wondering if you could write a litte more on this topic? I'd be very thankful if you could elaborate a little bit further. Thanks! 2022/01/29 1:27 Great post but I was wondering if you could write

Great post but I was wondering if you could write a litte more on this topic?
I'd be very thankful if you could elaborate a little bit further.
Thanks!

# doxycycline 100mg online https://doxycyline1st.com/
doxycycline 100mg tablets 2022/02/26 0:24 Jusidkid

doxycycline 100mg online https://doxycyline1st.com/
doxycycline 100mg tablets

# Wow, that's what I was looking for, what a material! existing here at this webpage, thanks admin of this website. 2022/03/25 7:33 Wow, that's what I was looking for, what a materia

Wow, that's what I was looking for, what a material!

existing here at this webpage, thanks admin of this website.

# Wow, that's what I was looking for, what a material! existing here at this webpage, thanks admin of this website. 2022/03/25 7:34 Wow, that's what I was looking for, what a materia

Wow, that's what I was looking for, what a material!

existing here at this webpage, thanks admin of this website.

# Wow, that's what I was looking for, what a material! existing here at this webpage, thanks admin of this website. 2022/03/25 7:35 Wow, that's what I was looking for, what a materia

Wow, that's what I was looking for, what a material!

existing here at this webpage, thanks admin of this website.

# Wow, that's what I was looking for, what a material! existing here at this webpage, thanks admin of this website. 2022/03/25 7:36 Wow, that's what I was looking for, what a materia

Wow, that's what I was looking for, what a material!

existing here at this webpage, thanks admin of this website.

# KKzOnqzvvkQH 2022/04/19 11:19 markus

http://imrdsoacha.gov.co/silvitra-120mg-qrms

# ujhhwdawbhhf 2022/05/08 9:00 whnqjq

hydroxychloroquine medication https://keys-chloroquinehydro.com/

# divymxreaueh 2022/05/23 16:42 rpfpcibo

https://erythromycinn.com/# erythromycin ophthalmic ointment for pink eye

# lasix online https://buylasix.icu/
furosemide 100mg 2022/06/24 16:54 LasixRx

lasix online https://buylasix.icu/
furosemide 100mg

# Diovan https://allpharm.store/ 2022/07/21 21:51 AllPharm

Diovan https://allpharm.store/

# ivermectin how to buy https://stromectolbestprice.com/ 2022/07/30 0:17 BestPrice

ivermectin how to buy https://stromectolbestprice.com/

# cvs prescription prices without insurance: https://medrxfast.com/ 2022/08/03 18:53 MedsRxFast

cvs prescription prices without insurance: https://medrxfast.com/

タイトル  
名前  
Url
コメント