Skip to content

Instantly share code, notes, and snippets.

@lekv
Created November 16, 2017 03:50
Show Gist options
  • Save lekv/508f540053340ffcf095d49b27c4317d to your computer and use it in GitHub Desktop.
Save lekv/508f540053340ffcf095d49b27c4317d to your computer and use it in GitHub Desktop.
#include <iostream>
#include <dirent.h>
#include <thread>
// Prepare: mkdir d; cd d; touch {0001.1000}
// Build with: g++ --std=c++11 -pthread -o main main.cpp
using namespace std;
int num_files(DIR* dir_stream) {
int n = 0;
struct dirent *entry;
while ((entry = readdir(dir_stream)) != nullptr) ++n;
return n;
}
void t_body(int iters, int expected) {
// This won't work, directory streams cannot be reused.
//DIR* dir_stream = opendir("d");
for (int i = 0; i < iters; ++i) {
DIR* dir_stream = opendir("d");
int actual = num_files(dir_stream);
closedir(dir_stream);
if (actual != expected) {
cout << "Got " << actual << " instead of " << expected << "." << endl;
return;
}
}
}
int main() {
DIR* d1 = opendir("d");
int expected = num_files(d1);
closedir(d1);
int num_iterations = 10000;
constexpr int num_threads = 10;
thread threads[num_threads];
for (int i = 0; i < num_threads; ++i) {
threads[i] = thread(t_body, num_iterations, expected);
}
cout << "Waiting for threads" << endl;
for (int i = 0; i < num_threads; ++i) {
threads[i].join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment