Repository navigation
Expand file tree
/
Copy pathtest_cpp_concurrency.py
More file actions
1932 lines (1590 loc) · 50.5 KB
/
Copy pathtest_cpp_concurrency.py
File metadata and controls
1932 lines (1590 loc) · 50.5 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Comprehensive C++ concurrency testing.
Tests threads, mutexes, atomics, condition variables, futures, async operations,
and various synchronization primitives.
"""
from pathlib import Path
from typing import cast
from unittest.mock import MagicMock
import pytest
from codebase_rag.graph_updater import GraphUpdater
from codebase_rag.parser_loader import load_parsers
@pytest.fixture
def cpp_concurrency_project(temp_repo: Path) -> Path:
"""Create a comprehensive C++ project with concurrency patterns."""
project_path = temp_repo / "cpp_concurrency_test"
project_path.mkdir()
# Create basic structure
(project_path / "src").mkdir()
(project_path / "include").mkdir()
return project_path
def test_thread_basics(
cpp_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test basic thread creation and management."""
test_file = cpp_concurrency_project / "thread_basics.cpp"
test_file.write_text(
"""
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <functional>
#include <sstream>
// Simple thread function
void simpleThreadFunction(int id) {
std::cout << "Thread " << id << " is running" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Thread " << id << " finished" << std::endl;
}
// Thread function with parameters
void threadWithParameters(int id, const std::string& message, double value) {
std::stringstream ss;
ss << "Thread " << id << ": " << message << " (value: " << value << ")" << std::endl;
std::cout << ss.str();
}
// Class with thread member function
class ThreadedWorker {
private:
int id_;
bool running_;
std::thread worker_thread_;
public:
ThreadedWorker(int id) : id_(id), running_(false) {}
~ThreadedWorker() {
stop();
}
void start() {
running_ = true;
worker_thread_ = std::thread(&ThreadedWorker::run, this);
}
void stop() {
if (running_) {
running_ = false;
if (worker_thread_.joinable()) {
worker_thread_.join();
}
}
}
bool isRunning() const { return running_; }
private:
void run() {
while (running_) {
std::cout << "Worker " << id_ << " processing..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
std::cout << "Worker " << id_ << " stopped" << std::endl;
}
};
// Thread pool pattern
class SimpleThreadPool {
private:
std::vector<std::thread> threads_;
std::vector<std::function<void()>> tasks_;
bool shutdown_ = false;
public:
SimpleThreadPool(size_t num_threads) {
for (size_t i = 0; i < num_threads; ++i) {
threads_.emplace_back([this, i] {
workerLoop(i);
});
}
}
~SimpleThreadPool() {
shutdown_ = true;
for (auto& thread : threads_) {
if (thread.joinable()) {
thread.join();
}
}
}
void addTask(std::function<void()> task) {
tasks_.push_back(std::move(task));
}
private:
void workerLoop(size_t worker_id) {
while (!shutdown_) {
if (!tasks_.empty()) {
auto task = tasks_.back();
tasks_.pop_back();
task();
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
};
// Thread local storage
thread_local int tls_counter = 0;
void incrementThreadLocal() {
tls_counter++;
std::cout << "Thread " << std::this_thread::get_id()
<< " counter: " << tls_counter << std::endl;
}
// Function demonstrating thread creation patterns
void demonstrateThreadBasics() {
std::cout << "=== Basic Thread Creation ===" << std::endl;
// Create thread with function
std::thread t1(simpleThreadFunction, 1);
t1.join();
// Create thread with lambda
std::thread t2([]() {
std::cout << "Lambda thread running" << std::endl;
});
t2.join();
// Create thread with parameters
std::thread t3(threadWithParameters, 3, "Hello from thread", 3.14);
t3.join();
// Multiple threads
std::vector<std::thread> threads;
for (int i = 0; i < 5; ++i) {
threads.emplace_back(simpleThreadFunction, i);
}
// Join all threads
for (auto& t : threads) {
t.join();
}
// Detached threads
std::thread detached([]() {
std::cout << "Detached thread running" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
});
detached.detach();
// Thread with class member function
ThreadedWorker worker(1);
worker.start();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
worker.stop();
// Thread pool usage
SimpleThreadPool pool(4);
for (int i = 0; i < 10; ++i) {
pool.addTask([i]() {
std::cout << "Task " << i << " executed" << std::endl;
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
// Thread local storage
std::vector<std::thread> tls_threads;
for (int i = 0; i < 3; ++i) {
tls_threads.emplace_back([]() {
for (int j = 0; j < 3; ++j) {
incrementThreadLocal();
}
});
}
for (auto& t : tls_threads) {
t.join();
}
}
// Thread utilities
void demonstrateThreadUtilities() {
std::cout << "=== Thread Utilities ===" << std::endl;
// Get thread ID
std::thread::id main_thread_id = std::this_thread::get_id();
std::cout << "Main thread ID: " << main_thread_id << std::endl;
// Hardware concurrency
unsigned int num_cores = std::thread::hardware_concurrency();
std::cout << "Hardware concurrency: " << num_cores << " cores" << std::endl;
// Thread sleep
auto start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::cout << "Slept for " << duration.count() << " milliseconds" << std::endl;
// Thread yield
std::thread yielder([]() {
for (int i = 0; i < 1000; ++i) {
if (i % 100 == 0) {
std::this_thread::yield(); // Give other threads a chance
}
}
});
yielder.join();
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_concurrency_project.name
# Expected thread-related classes and functions
expected_entities = [
f"{project_name}.thread_basics.simpleThreadFunction",
f"{project_name}.thread_basics.threadWithParameters",
f"{project_name}.thread_basics.ThreadedWorker",
f"{project_name}.thread_basics.SimpleThreadPool",
f"{project_name}.thread_basics.demonstrateThreadBasics",
]
# Get all node creation calls
all_calls = mock_ingestor.ensure_node_batch.call_args_list
class_calls = [call for call in all_calls if call[0][0] == "Class"]
function_calls = [call for call in all_calls if call[0][0] == "Function"]
method_calls = [call for call in all_calls if call[0][0] == "Method"]
created_entities = {
call[0][1]["qualified_name"]
for call in class_calls + function_calls + method_calls
}
# Verify expected entities were created
found_entities = [
entity for entity in expected_entities if entity in created_entities
]
assert len(found_entities) >= 4, (
f"Expected at least 4 thread entities, found {len(found_entities)}: {found_entities}"
)
def test_mutex_and_locks(
cpp_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test mutex and lock mechanisms."""
test_file = cpp_concurrency_project / "mutex_locks.cpp"
test_file.write_text(
"""
#include <iostream>
#include <thread>
#include <mutex>
#include <shared_mutex>
#include <vector>
#include <chrono>
// Global mutex for demonstration
std::mutex global_mutex;
std::recursive_mutex recursive_mutex;
std::timed_mutex timed_mutex;
std::shared_mutex shared_mutex;
// Shared resource protected by mutex
class Counter {
private:
mutable std::mutex mutex_;
int value_;
public:
Counter() : value_(0) {}
void increment() {
std::lock_guard<std::mutex> lock(mutex_);
value_++;
}
void decrement() {
std::lock_guard<std::mutex> lock(mutex_);
value_--;
}
int getValue() const {
std::lock_guard<std::mutex> lock(mutex_);
return value_;
}
// Try to increment with timeout
bool tryIncrement(int timeout_ms) {
std::unique_lock<std::mutex> lock(mutex_, std::defer_lock);
if (lock.try_lock_for(std::chrono::milliseconds(timeout_ms))) {
value_++;
return true;
}
return false;
}
};
// Bank account with multiple mutexes
class BankAccount {
private:
mutable std::mutex balance_mutex_;
mutable std::mutex history_mutex_;
double balance_;
std::vector<std::string> history_;
public:
BankAccount(double initial_balance) : balance_(initial_balance) {}
void deposit(double amount) {
std::lock_guard<std::mutex> lock(balance_mutex_);
balance_ += amount;
std::lock_guard<std::mutex> history_lock(history_mutex_);
history_.push_back("Deposit: " + std::to_string(amount));
}
bool withdraw(double amount) {
std::lock_guard<std::mutex> lock(balance_mutex_);
if (balance_ >= amount) {
balance_ -= amount;
std::lock_guard<std::mutex> history_lock(history_mutex_);
history_.push_back("Withdrawal: " + std::to_string(amount));
return true;
}
return false;
}
double getBalance() const {
std::lock_guard<std::mutex> lock(balance_mutex_);
return balance_;
}
// Transfer with deadlock avoidance
static void transfer(BankAccount& from, BankAccount& to, double amount) {
// Use std::lock to avoid deadlock
std::unique_lock<std::mutex> lock1(from.balance_mutex_, std::defer_lock);
std::unique_lock<std::mutex> lock2(to.balance_mutex_, std::defer_lock);
std::lock(lock1, lock2);
if (from.balance_ >= amount) {
from.balance_ -= amount;
to.balance_ += amount;
}
}
};
// Read-write lock pattern
class SharedData {
private:
mutable std::shared_mutex mutex_;
std::vector<int> data_;
public:
void write(int value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
data_.push_back(value);
}
void modify(size_t index, int value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
if (index < data_.size()) {
data_[index] = value;
}
}
int read(size_t index) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
if (index < data_.size()) {
return data_[index];
}
return -1;
}
size_t size() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return data_.size();
}
std::vector<int> getAll() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return data_; // Return copy
}
};
// Recursive mutex example
class RecursiveResource {
private:
mutable std::recursive_mutex mutex_;
int value_;
public:
RecursiveResource() : value_(0) {}
void setValue(int v) {
std::lock_guard<std::recursive_mutex> lock(mutex_);
value_ = v;
logValue(); // Recursive call
}
void logValue() {
std::lock_guard<std::recursive_mutex> lock(mutex_);
std::cout << "Value is: " << value_ << std::endl;
}
int getValue() const {
std::lock_guard<std::recursive_mutex> lock(mutex_);
return value_;
}
};
// Scoped lock (C++17) for multiple mutexes
void demonstrateScopedLock() {
std::mutex mutex1, mutex2, mutex3;
{
std::scoped_lock lock(mutex1, mutex2, mutex3);
// All mutexes locked atomically
std::cout << "All mutexes locked with scoped_lock" << std::endl;
} // All mutexes unlocked
}
// Once flag pattern
std::once_flag init_flag;
void initializeOnce() {
std::call_once(init_flag, []() {
std::cout << "Initialization performed only once" << std::endl;
});
}
void demonstrateMutexPatterns() {
std::cout << "=== Mutex and Lock Patterns ===" << std::endl;
// Basic mutex with lock_guard
{
std::lock_guard<std::mutex> lock(global_mutex);
std::cout << "Protected section with lock_guard" << std::endl;
}
// Unique lock with deferred locking
{
std::unique_lock<std::mutex> lock(global_mutex, std::defer_lock);
// Do some work
lock.lock();
std::cout << "Protected section with unique_lock" << std::endl;
lock.unlock();
// Do more work
}
// Try lock
{
std::unique_lock<std::mutex> lock(global_mutex, std::try_to_lock);
if (lock.owns_lock()) {
std::cout << "Successfully acquired lock with try_lock" << std::endl;
}
}
// Timed mutex
{
if (timed_mutex.try_lock_for(std::chrono::milliseconds(100))) {
std::cout << "Acquired timed mutex" << std::endl;
timed_mutex.unlock();
}
}
// Counter with multiple threads
Counter counter;
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back([&counter]() {
for (int j = 0; j < 1000; ++j) {
counter.increment();
}
});
}
for (auto& t : threads) {
t.join();
}
std::cout << "Counter value: " << counter.getValue() << std::endl;
// Bank account transfers
BankAccount account1(1000.0);
BankAccount account2(500.0);
std::thread t1([&account1, &account2]() {
for (int i = 0; i < 10; ++i) {
BankAccount::transfer(account1, account2, 50.0);
}
});
std::thread t2([&account1, &account2]() {
for (int i = 0; i < 10; ++i) {
BankAccount::transfer(account2, account1, 30.0);
}
});
t1.join();
t2.join();
std::cout << "Account 1 balance: " << account1.getBalance() << std::endl;
std::cout << "Account 2 balance: " << account2.getBalance() << std::endl;
// Shared data with read-write lock
SharedData shared_data;
// Writers
std::vector<std::thread> writers;
for (int i = 0; i < 3; ++i) {
writers.emplace_back([&shared_data, i]() {
for (int j = 0; j < 5; ++j) {
shared_data.write(i * 10 + j);
}
});
}
// Readers
std::vector<std::thread> readers;
for (int i = 0; i < 5; ++i) {
readers.emplace_back([&shared_data]() {
for (int j = 0; j < 10; ++j) {
size_t size = shared_data.size();
if (size > 0) {
shared_data.read(j % size);
}
}
});
}
for (auto& t : writers) t.join();
for (auto& t : readers) t.join();
// Recursive mutex
RecursiveResource recursive_resource;
recursive_resource.setValue(42);
// Once flag
std::vector<std::thread> init_threads;
for (int i = 0; i < 5; ++i) {
init_threads.emplace_back(initializeOnce);
}
for (auto& t : init_threads) t.join();
// Scoped lock demo
demonstrateScopedLock();
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_concurrency_project.name
# Expected mutex-related classes
expected_classes = [
f"{project_name}.mutex_locks.Counter",
f"{project_name}.mutex_locks.BankAccount",
f"{project_name}.mutex_locks.SharedData",
f"{project_name}.mutex_locks.RecursiveResource",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify expected classes were created
found_classes = [cls for cls in expected_classes if cls in created_classes]
assert len(found_classes) >= 3, (
f"Expected at least 3 mutex-related classes, found {len(found_classes)}: {found_classes}"
)
def test_atomics_and_memory_ordering(
cpp_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test atomic operations and memory ordering."""
test_file = cpp_concurrency_project / "atomics.cpp"
test_file.write_text(
"""
#include <iostream>
#include <atomic>
#include <thread>
#include <vector>
#include <chrono>
// Basic atomic types
std::atomic<int> atomic_counter{0};
std::atomic<bool> atomic_flag{false};
std::atomic<double> atomic_double{0.0};
// Custom atomic structure
struct AtomicData {
int x, y;
};
std::atomic<AtomicData> atomic_struct{{0, 0}};
// Lock-free counter
class LockFreeCounter {
private:
std::atomic<int> count_;
public:
LockFreeCounter() : count_(0) {}
void increment() {
count_.fetch_add(1, std::memory_order_relaxed);
}
void decrement() {
count_.fetch_sub(1, std::memory_order_relaxed);
}
int get() const {
return count_.load(std::memory_order_relaxed);
}
bool compareAndSwap(int expected, int desired) {
return count_.compare_exchange_strong(expected, desired);
}
};
// Spinlock using atomic flag
class SpinLock {
private:
std::atomic_flag lock_ = ATOMIC_FLAG_INIT;
public:
void lock() {
while (lock_.test_and_set(std::memory_order_acquire)) {
// Spin
}
}
void unlock() {
lock_.clear(std::memory_order_release);
}
};
// Lock-free stack
template<typename T>
class LockFreeStack {
private:
struct Node {
T data;
Node* next;
Node(T value) : data(std::move(value)), next(nullptr) {}
};
std::atomic<Node*> head_;
public:
LockFreeStack() : head_(nullptr) {}
~LockFreeStack() {
while (Node* old_head = head_.load()) {
head_.store(old_head->next);
delete old_head;
}
}
void push(T value) {
Node* new_node = new Node(std::move(value));
new_node->next = head_.load();
while (!head_.compare_exchange_weak(new_node->next, new_node)) {
// Retry
}
}
bool pop(T& result) {
Node* old_head = head_.load();
while (old_head && !head_.compare_exchange_weak(old_head, old_head->next)) {
// Retry
}
if (old_head) {
result = old_head->data;
delete old_head;
return true;
}
return false;
}
};
// Memory ordering examples
class MemoryOrderingDemo {
private:
std::atomic<bool> flag_{false};
std::atomic<int> data_{0};
public:
// Producer with release semantics
void producer() {
data_.store(42, std::memory_order_relaxed);
flag_.store(true, std::memory_order_release);
}
// Consumer with acquire semantics
int consumer() {
while (!flag_.load(std::memory_order_acquire)) {
// Wait
}
return data_.load(std::memory_order_relaxed);
}
// Sequential consistency example
void sequentialConsistency() {
data_.store(100); // Default is memory_order_seq_cst
flag_.store(true);
}
};
// Atomic shared pointer
template<typename T>
class AtomicSharedPtr {
private:
std::atomic<std::shared_ptr<T>> ptr_;
public:
AtomicSharedPtr() = default;
void store(std::shared_ptr<T> new_ptr) {
std::atomic_store(&ptr_, new_ptr);
}
std::shared_ptr<T> load() const {
return std::atomic_load(&ptr_);
}
void exchange(std::shared_ptr<T> new_ptr) {
std::atomic_exchange(&ptr_, new_ptr);
}
};
void demonstrateAtomicOperations() {
std::cout << "=== Atomic Operations ===" << std::endl;
// Basic atomic operations
atomic_counter.store(10);
int old_value = atomic_counter.exchange(20);
std::cout << "Exchanged " << old_value << " with 20" << std::endl;
// Fetch and add
int result = atomic_counter.fetch_add(5);
std::cout << "Fetch and add: old=" << result << ", new=" << atomic_counter.load() << std::endl;
// Compare and exchange
int expected = 25;
int desired = 30;
if (atomic_counter.compare_exchange_strong(expected, desired)) {
std::cout << "CAS succeeded" << std::endl;
}
// Lock-free counter with multiple threads
LockFreeCounter counter;
std::vector<std::thread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back([&counter]() {
for (int j = 0; j < 10000; ++j) {
counter.increment();
}
});
}
for (auto& t : threads) {
t.join();
}
std::cout << "Lock-free counter: " << counter.get() << std::endl;
// Spinlock test
SpinLock spinlock;
int shared_value = 0;
threads.clear();
for (int i = 0; i < 5; ++i) {
threads.emplace_back([&spinlock, &shared_value]() {
for (int j = 0; j < 1000; ++j) {
spinlock.lock();
shared_value++;
spinlock.unlock();
}
});
}
for (auto& t : threads) {
t.join();
}
std::cout << "Spinlock protected value: " << shared_value << std::endl;
// Lock-free stack
LockFreeStack<int> stack;
// Producer threads
threads.clear();
for (int i = 0; i < 3; ++i) {
threads.emplace_back([&stack, i]() {
for (int j = 0; j < 5; ++j) {
stack.push(i * 10 + j);
}
});
}
// Consumer thread
threads.emplace_back([&stack]() {
int value;
int count = 0;
while (count < 15) {
if (stack.pop(value)) {
std::cout << "Popped: " << value << std::endl;
count++;
}
}
});
for (auto& t : threads) {
t.join();
}
// Memory ordering
MemoryOrderingDemo ordering_demo;
std::thread producer([&ordering_demo]() {
ordering_demo.producer();
});
std::thread consumer([&ordering_demo]() {
int value = ordering_demo.consumer();
std::cout << "Consumer got: " << value << std::endl;
});
producer.join();
consumer.join();
// Atomic operations on custom types
AtomicData data{10, 20};
atomic_struct.store(data);
AtomicData loaded = atomic_struct.load();
std::cout << "Atomic struct: x=" << loaded.x << ", y=" << loaded.y << std::endl;
// Check if types are lock-free
std::cout << "atomic<int> is lock-free: " << atomic_counter.is_lock_free() << std::endl;
std::cout << "atomic<AtomicData> is lock-free: " << atomic_struct.is_lock_free() << std::endl;
}
// Performance comparison
void compareAtomicVsMutex() {
const int iterations = 1000000;
// Atomic counter
std::atomic<int> atomic_cnt{0};
auto start = std::chrono::high_resolution_clock::now();
std::vector<std::thread> threads;
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&atomic_cnt, iterations]() {
for (int j = 0; j < iterations; ++j) {
atomic_cnt.fetch_add(1);
}
});
}
for (auto& t : threads) {
t.join();
}
auto atomic_time = std::chrono::high_resolution_clock::now() - start;
// Mutex counter
int mutex_cnt = 0;
std::mutex mutex;
start = std::chrono::high_resolution_clock::now();
threads.clear();
for (int i = 0; i < 4; ++i) {
threads.emplace_back([&mutex_cnt, &mutex, iterations]() {
for (int j = 0; j < iterations; ++j) {
std::lock_guard<std::mutex> lock(mutex);
mutex_cnt++;
}
});
}
for (auto& t : threads) {
t.join();
}
auto mutex_time = std::chrono::high_resolution_clock::now() - start;
std::cout << "Atomic time: " << std::chrono::duration_cast<std::chrono::milliseconds>(atomic_time).count() << "ms" << std::endl;
std::cout << "Mutex time: " << std::chrono::duration_cast<std::chrono::milliseconds>(mutex_time).count() << "ms" << std::endl;
}
"""
)
parsers, queries = load_parsers()
updater = GraphUpdater(
ingestor=mock_ingestor,
repo_path=cpp_concurrency_project,
parsers=parsers,
queries=queries,
)
updater.run()
project_name = cpp_concurrency_project.name
# Expected atomic-related classes
expected_classes = [
f"{project_name}.atomics.LockFreeCounter",
f"{project_name}.atomics.SpinLock",
f"{project_name}.atomics.LockFreeStack",
f"{project_name}.atomics.MemoryOrderingDemo",
]
# Get all Class node creation calls
class_calls = [
call
for call in mock_ingestor.ensure_node_batch.call_args_list
if call[0][0] == "Class"
]
created_classes = {call[0][1]["qualified_name"] for call in class_calls}
# Verify expected classes were created
found_classes = [cls for cls in expected_classes if cls in created_classes]
assert len(found_classes) >= 3, (
f"Expected at least 3 atomic-related classes, found {len(found_classes)}: {found_classes}"
)
def test_condition_variables_and_futures(
cpp_concurrency_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test condition variables, futures, and promises."""
test_file = cpp_concurrency_project / "condition_futures.cpp"
test_file.write_text(
"""
#include <iostream>