/**
*
* @file CCppAndThreads_a.cpp
*
* @authors D. Mathieu
*
* @date 03/02/2010
*
* @version V3.0
*
* @brief strtok() thread-safe ?
*
**/
#include <iostream>
#include <sstream>
#include <string>
#include <cstring> // strcpy(), strtok()
#include <vector>
#include <boost/thread/thread.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/tr1/functional.hpp> // ou <functional> pour bind()
using namespace std;
using namespace boost;
enum {KErrArg = 253 };
namespace
{
typedef vector <char *> VpChar;
const char * punct = " ";
mutex io_Mtx;
void fThread (const string * param)
{
char * oneString = new char [param->size() + 1];
strcpy (oneString, param->c_str());
/* Affichage de la NTCTS locale * /
{
lock_guard <mutex> oneLock (io_Mtx);
cout << oneString << endl;
}
/* */
VpChar tab;
/* * /
for (tab.push_back (strtok (oneString, punct));
tab.back();
tab.push_back (strtok (0, punct)));
tab.pop_back(); // suppression du dernier pointeur (nul)
/* */
/* */
char * buffer;
for (tab.push_back (strtok_r (oneString, punct, &buffer));
tab.back();
tab.push_back (strtok_r (0, punct, &buffer)));
tab.pop_back(); // suppression du dernier pointeur (nul)
/* * /
/* */
{
lock_guard <mutex> oneLock (io_Mtx);
cout << "Nombre de mots : " << tab.size() << '\n';
}
/* */
delete [] oneString;
/* */
} // fThread()
} // namespace
int main (int argc, char * argv [])
{
if (2 != argc)
{
cerr << "Usage : " << argv [0] << " <Nb_threads>\n";
return KErrArg;
}
unsigned nbThreads;
{
istringstream is (argv [1]);
is >> nbThreads;
}
string line;
for (unsigned i (200000) ; i--; ) line += "Toto ";
thread_group groupThreads;
for (unsigned i = nbThreads; i--; )
{
groupThreads.add_thread (new thread (bind <void> (fThread, & line)));
}
groupThreads.join_all ();
return 0;
} // main()