File: test2.cpp

package info (click to toggle)
concurrentqueue 1.0.2%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,244 kB
  • sloc: cpp: 13,006; makefile: 82; ansic: 67; python: 46; sh: 18
file content (46 lines) | stat: -rw-r--r-- 901 bytes parent folder | download | duplicates (2)
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
#include <iostream>
#include <cassert>
#include "concurrentqueue/concurrentqueue.h"

int main()
{
	moodycamel::ConcurrentQueue<int> q;
	int dequeued[100] = { 0 };
	std::thread threads[20];

	for (int i = 0; i != 10; ++i) {
		threads[i] = std::thread([&](int i) {
			for (int j = 0; j != 10; ++j) {
				q.enqueue(i * 10 + j);
			}
		}, i);
	}

	// Consumers
	for (int i = 10; i != 20; ++i) {
		threads[i] = std::thread([&]() {
			int item;
			for (int j = 0; j != 20; ++j) {
				if (q.try_dequeue(item)) {
					++dequeued[item];
				}
			}
		});
	}

	// Wait for all threads
	for (int i = 0; i != 20; ++i) {
		threads[i].join();
	}

	// Collect any leftovers (could be some if e.g. consumers finish before producers)
	int item;
	while (q.try_dequeue(item)) {
		++dequeued[item];
	}

	// Make sure everything went in and came back out!
	for (int i = 0; i != 100; ++i) {
		assert(dequeued[i] == 1);
	}
}