Skip to content

Instantly share code, notes, and snippets.

@youxkei
Created June 19, 2017 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save youxkei/29231c044793e8f907059d7d31523e9f to your computer and use it in GitHub Desktop.
Save youxkei/29231c044793e8f907059d7d31523e9f to your computer and use it in GitHub Desktop.
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
using std::cout;
using std::cerr;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::flush;
using std::vector;
using boost::interprocess::file_lock;
using boost::interprocess::scoped_lock;
constexpr int CHILDREN_NUM = 2048;
void count_up() {
file_lock flock("lock");
scoped_lock<file_lock> slock(flock);
int count;
ifstream("count") >> count;
ofstream("count") << (count + 1);
}
int main(){
vector<pid_t> pids;
for (int i = 0; i < CHILDREN_NUM; ++i) {
pid_t child_pid = fork();
if (child_pid == -1) {
cerr << "cannot create a child process" << endl;
return 1;
} else if (child_pid == 0) {
count_up();
return 0;
} else {
pids.push_back(child_pid);
}
}
for (pid_t pid : pids) waitpid(pid, nullptr, 0);
int count;
{ ifstream("count") >> count; }
cout << count << endl;
return 0;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment