Skip to content

Instantly share code, notes, and snippets.

@jameskyle
Created April 6, 2014 02:37
Show Gist options
  • Select an option

  • Save jameskyle/10000811 to your computer and use it in GitHub Desktop.

Select an option

Save jameskyle/10000811 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <future>
#include <thread>
#include <algorithm>
#include <cstdlib>
#include <sstream>
#include <mutex>
#include <map>
#include <string>
#define BOOST_FILESYSTEM_NO_DEPRECATED
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
namespace fs = boost::filesystem;
std::mutex m;
typedef std::pair<uint32_t, fs::path> hash_pair ;
//typedef std::pair<uint32_t, std::string> hash_pair ;
void get_hashes(
fs::path &root,
std::vector< std::future<hash_pair> > &results
) {
const fs::recursive_directory_iterator end;
std::for_each(
fs::recursive_directory_iterator(root),
end,
[&results](const fs::directory_entry &entry) {
results.push_back(async(std::launch::async, [&entry]() -> hash_pair {
hash_pair hp;
m.lock();
std::cout << "Starting new thread: " << std::this_thread::get_id() << std::endl;
m.unlock();
sleep(5);
// the second value for the pair ends up being trash or empty strings.
hp = std::make_pair(rand(), entry.path());
// below works fine
//hp = std::make_pair(rand(), std::string{"a string value"});
return hp;
}));
});
}
int main()
{
std::mutex m;
std::vector<std::future<hash_pair>> futures;
std::map<uint32_t, fs::path> hashes;
fs::path root = "./data";
get_hashes(root, futures);
for (auto &result : futures) {
auto pair = result.get();
hashes[pair.first] = pair.second;
}
for (auto &result : hashes) {
std::cout << result.first << " : " << result.second << std::endl;
}
std::cout << "number of hashes: " << hashes.size() << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment