マルチスレッドとstl

スレッドの中でvectorに次々につっこんでいくプログラム。

#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace std;

vector<int> v;

void greetingWithID(int i) {
  v.push_back(i);
}

int main(int argc, char *argv[]) {
  int n = 1000;
  boost::thread_group agroup;
  for (int i = 0; i < n; i++) {
	agroup.create_thread(boost::bind(greetingWithID, i));
  }
  agroup.join_all();

  BOOST_FOREACH(int i, v) {
	cout << i << endl;
  }
  return 0;
}

ときどき、せぐふぉで死ぬ。死なないときもある(困ったものだ)。

/tmp% ./a.out
a.out(97049,0xb0207000) malloc: *** error for object 0x100b50: double free
*** set a breakpoint in malloc_error_break to debug
zsh: segmentation fault  ./a.out

排他制御ができてないからかなー。

追記

mutexスレッド間の同期をしてくれるboost::mutexというのがあるらしく、こいつを使うと死ななくなった。

#include <iostream>
#include <vector>
#include <boost/foreach.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace std;

vector<int> v;
boost::mutex key;

void greetingWithID(int i) {
  boost::mutex::scoped_lock lock(key);
  v.push_back(i);
}

int main(int argc, char *argv[]) {
  int n = 1000;
  boost::thread_group agroup;
  for (int i = 0; i < n; i++) {
	agroup.create_thread(boost::bind(greetingWithID, i));
  }
  agroup.join_all();

  BOOST_FOREACH(int i, v) {
	cout << i << endl;
  }
  return 0;
}

参考