File: test3.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 (50 lines) | stat: -rw-r--r-- 1,093 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
47
48
49
50
#include <iostream>
#include <cassert>
#include "concurrentqueue/concurrentqueue.h"

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

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

	// Consumers
	for (int i = 10; i != 20; ++i) {
		threads[i] = std::thread([&]() {
			int items[20];
			for (std::size_t count = q.try_dequeue_bulk(items, 20); count != 0; --count) {
				++dequeued[items[count - 1]];
			}
		});
	}

	// 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 items[10];
	std::size_t count;
	while ((count = q.try_dequeue_bulk(items, 10)) != 0) {
		for (std::size_t i = 0; i != count; ++i) {
			++dequeued[items[i]];
		}
	}

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