Skip to content

Instantly share code, notes, and snippets.

@JVero
Created December 23, 2018 07:42
Show Gist options
  • Save JVero/362b734c17ffaa31118b1eaae01d41c2 to your computer and use it in GitHub Desktop.
Save JVero/362b734c17ffaa31118b1eaae01d41c2 to your computer and use it in GitHub Desktop.
#include<fstream>
#include<iostream>
#include<thread>
#include<string>
#include<cstdio>
void write(std::string filename, std::string message){
std::ofstream f;
f.open(filename, std::ofstream::out | std::ofstream::app);
for (auto i = 0; i < 10; i++) {
f << filename << " " << message << std::endl;
f.flush();
}
}
int numlines(std::string filename) {
std::ifstream f{filename};
std::string token;
int counter;
for (counter=0;std::getline(f, token);counter++){}
return counter;
}
constexpr int q = 30;
int main() {
constexpr int nl = q * 10;
for (int i = 0; i < 1<<20; i++){
std::thread ths[q];
for (int j = 0; j < q; j++)
{
ths[j] = std::thread{write, "h.txt", std::string{(char)(65+j)}};
}
for (int j = 0; j < q; j++)
{
ths[j].join();
}
if (numlines("h.txt") != nl ){
std::cout << "Not thread safe!" << std::endl;
}
else {
std::cout << i << std::endl;
}
std::remove("h.txt");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment