Created
June 19, 2017 19:04
-
-
Save youxkei/29231c044793e8f907059d7d31523e9f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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