#include #include "SWTLocker.h" #include "ContainerThread.h" #include "Random.h" #include "GlobalConfigFile.h" #include "MicroSleep.h" // This is a test program aimed at SWTLocker.h // g++ -Wall -O4 -lpthread SWTLockerTest.C LogFile.C shared.a // Run the program, it should run for a while, then fail an assertion // IMMEDIATELY AFTER printing "about to explode!" // Change one of the contansts in the code to reconfigure this. // // We create a very simple Data struct. This is what we are going to protect // with the mutex. We create several threads. Each one will repeatedly // acquire and release the lock. Each will sleep for a random amount of time // in and outside of the lock, simulating real work. struct Data { int64_t plus; int64_t minus; Data() : plus(0), minus(0) { } }; SWTLocker< Data > data; int main(int, char **) { configItemsComplete(); const int threadCount = 5; const int maxInLockTime = 1000; const int maxOutOfLockTime = 2 * threadCount * maxInLockTime; const int iterationsPerThread = 100; for (int threadId = 0; threadId < threadCount; threadId++) { const bool writer = (threadId == 0); IContainerThread *const thread = writer ?IContainerThread::create("RW Thread", false) :IContainerThread::create("RO Thread", true); auto job = [=]() { if (writer) data.setWriteThread(); for (int iteration = 0; iteration < iterationsPerThread; iteration++) { int sleepTime = getRandom31() % maxOutOfLockTime; std::string msg = cMicroTimeString(getMicroTime()) + ": Thread #" + ntoa(threadId) + ", iteration #" + ntoa(iteration) + ", sleeping " + addCommas(sleepTime) + "ms before trying to lock.\n"; std::cout<plus == -readLock->minus); microSleep(sleepTime * 1000LL); assert(readLock->plus == -readLock->minus); if (writer) { msg = cMicroTimeString(getMicroTime()) + ": Thread #" + ntoa(threadId) + ", iteration #" + ntoa(iteration) + ", about to WRITE lock.\n"; std::cout<plus++; microSleep(sleepTime * 1000LL); writeLock->minus--; } } std::string msg = cMicroTimeString(getMicroTime()) + ": Thread #" + ntoa(threadId) + (writer?" is done writing.\n":" is about to explode!\n"); std::cout<addLambdaToQueue(job); } while (true) sleep(10); }