File: stabtest.cpp

package info (click to toggle)
readerwriterqueue 1.0.6-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 428 kB
  • sloc: cpp: 3,290; makefile: 79
file content (80 lines) | stat: -rw-r--r-- 2,245 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "../../readerwriterqueue.h"
#include "../common/simplethread.h"

using namespace moodycamel;

#include <cstdlib>
#include <exception>
#include <fstream>
#include <cstdlib>		// rand()
//#include <unistd.h>		// usleep()

void unpredictableDelay(int extra = 0)
{
/*	if ((rand() & 4095) == 0) {
		usleep(2000 + extra);	// in microseconds
	}*/
}

int main(int argc, char** argv)
{
	// Disable buffering (so that when run in, e.g., Sublime Text, the output appears as it is written)
	std::setvbuf(stdout, nullptr, _IONBF, 0);
	
	std::printf("Running stability test for moodycamel::ReaderWriterQueue.\n");
	std::printf("Logging to 'log.txt'. Press CTRL+C to quit.\n\n");
	
	
	std::ofstream log("log.txt");

	try {
		for (unsigned int i = 0; true; ++i) {
			log << "Test #" << i << std::endl;
			std::printf("Test #%d\n", i);

			ReaderWriterQueue<unsigned long long> q((rand() % 32) + 1);
	
			SimpleThread writer([&]() {
				for (unsigned long long j = 0; j < 1024ULL * 1024ULL * 32ULL; ++j) {
					unpredictableDelay(500);
					q.enqueue(j);
				}
			});
	
			SimpleThread reader([&]() {
				bool canLog = true;
				unsigned long long element;
				for (unsigned long long j = 0; j < 1024ULL * 1024ULL * 32ULL;) {
					if (canLog && (j & (1024 * 1024 * 16 - 1)) == 0) {
						log << "  ... iteration " << j << std::endl;
						std::printf("  ... iteration %llu\n", j);
						canLog = false;
					}
					unpredictableDelay();
					if (q.try_dequeue(element)) {
						if (element != j) {
							log << "  ERROR DETECTED: Expected to read " << j << " but found " << element << std::endl;
							std::printf("  ERROR DETECTED: Expected to read %llu but found %llu", j, element);
						}
						++j;
						canLog = true;
					}
				}
				if (q.try_dequeue(element)) {
					log << "  ERROR DETECTED: Expected queue to be empty" << std::endl;
					std::printf("  ERROR DETECTED: Expected queue to be empty\n");
				}
			});
		
			writer.join();
			reader.join();
		}
	}
	catch (std::exception const& ex) {
		log << "  ERROR DETECTED: Exception thrown: " << ex.what() << std::endl;
		std::printf("  ERROR DETECTED: Exception thrown: %s\n", ex.what());
	}
	
	return 0;
}