-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathmultithread.cpp
More file actions
75 lines (61 loc) · 1.38 KB
/
Copy pathmultithread.cpp
File metadata and controls
75 lines (61 loc) · 1.38 KB
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
// Observable Library
// Copyright (c) 2016-present David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#include "obs/signal.h"
#include "test.h"
#include <atomic>
#include <thread>
#include <vector>
const int N = 1;
class A {
int m_code;
public:
A(int code) : m_code(code) {
EXPECT_TRUE(m_code >= 0);
}
~A() {
EXPECT_TRUE(m_code >= 0);
m_code = -1;
}
void on_signal(int value) {
EXPECT_TRUE(m_code >= 0);
}
};
int main() {
obs::safe_signal<void(int)> signal;
std::vector<std::thread> threads;
std::atomic<int> count = { 0 };
signal.connect([&count](int){ ++count; });
A b(1);
signal.connect(&A::on_signal, &b);
for (int i=0; i<500*N; ++i) {
// Emit the signal
if ((i%2) == 0) {
threads.push_back(
std::thread(
[&signal](){
for (int c=100*N; c>0; --c) {
signal(c);
}
}));
}
// Observe the signal
else {
threads.push_back(
std::thread(
[&signal, i](){
A a(i);
obs::scoped_connection conn = signal.connect(&A::on_signal, &a);
for (int c=10*N; c>0; --c) {
signal(i);
}
}));
}
signal(1000+i);
}
for (auto& thread : threads)
thread.join();
std::cout << "Count = " << count << "\n";
}