When I studied Android AsyncTask, especially
when Serialexecutor was the norm, I found how
Google engineers have designed to serialize
execution of multiple threads. My original
code simulating similar effects using Java
was done more than a decade ago. Here it is.
Here we go.
//============================================================================
// Name : ClassLevelLockingThreadSerialization.cpp
// Author : Som
// Version :
// Copyright : som-itsolutions
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <future>
#include <chrono>
#include <mutex>
class ExampleClass {
private:
static std::mutex classMutex;
public:
static void testMethod(const std::string& threadName) {
std::lock_guard<std::mutex> lock(classMutex);
for (int i = 0; i < 10; i++) {
std::cout
<< "The testMethod for "
<< threadName
<< std::endl;
std::this_thread::sleep_for(
std::chrono::seconds(1)
);
}
}
};
std::mutex ExampleClass::classMutex;
int main() {
auto f1 = std::async(
std::launch::async,
ExampleClass::testMethod,
"Thread 1"
);
auto f2 = std::async(
std::launch::async,
ExampleClass::testMethod,
"Thread 2"
);
f1.get();
f2.get();
}

No comments:
Post a Comment