Multithreaded file writer in C++
mul·ti·thread·ing
A technique by which a single set of code can be used by several processors at different stages of execution.
The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex or several mutexes (since C++17) for the duration of a scoped block.
When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.
If several mutexes are given, deadlock avoidance algorithm is used as if by std::lock. (since C++17)
The lock_guard class is non-copyable.
A technique by which a single set of code can be used by several processors at different stages of execution.
The class lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex or several mutexes (since C++17) for the duration of a scoped block.
When a lock_guard object is created, it attempts to take ownership of the mutex it is given. When control leaves the scope in which the lock_guard object was created, the lock_guard is destructed and the mutex is released.
If several mutexes are given, deadlock avoidance algorithm is used as if by std::lock. (since C++17)
The lock_guard class is non-copyable.
#include "stdafx.h"
#include <mutex>
CWinApp theApp;
using namespace std;
const int size_ = 100; //thread array size
std::mutex mymutex;
void printRailLock(int id) {
printf("#ID :%d", id);
lock_guard<std::mutex> lk(mymutex); // <- this is the lock
CStdioFile lastLog;
CString logfiledb{ "_FILE_2.txt" };
CString str;
str.Format(L"%d\n", id);
bool opend = lastLog.Open(logfiledb, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate);
if (opend) {
lastLog.SeekToEnd();
lastLog.WriteString(str);
lastLog.Flush();
lastLog.Close();
}
}
int main()
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(nullptr);
if (hModule != nullptr)
{
if (!AfxWinInit(hModule, nullptr, ::GetCommandLine(), 0))
{
wprintf(L"Fatal Error: MFC initialization failed\n");
nRetCode = 1;
}
else
{
std::thread threads[size_];
for (int i = 0; i < size_; ++i) {
threads[i] = std::thread(printRailLock, i + 1);
Sleep(500);
}
for (auto& th : threads) {
//th.hardware_concurrency();
th.join();
}
}
}
else
{
wprintf(L"Fatal Error: GetModuleHandle failed\n");
nRetCode = 1;
}
return nRetCode;
}
Comments
Post a Comment