brintos

brintos / llvm-project-archived public Read only

0
0
Text · 1.7 KiB · fe4fb11 Raw
69 lines · cpp
1#include <condition_variable>2#include <iostream>3#include <mutex>4#include <thread>5 6std::mutex mtx;7std::condition_variable cv;8int ready_thread_id = 0;9int signal_main_thread = 0;10 11void worker(int id) {12  std::cout << "Worker " << id << " executing..." << std::endl;13 14  // lldb test should change signal_main_thread to true to break the loop.15  while (!signal_main_thread) {16    std::this_thread::sleep_for(std::chrono::milliseconds(10));17  }18 19  // Signal the main thread to continue main thread20  {21    std::lock_guard<std::mutex> lock(mtx);22    ready_thread_id = id; // break worker thread here23  }24  cv.notify_one();25 26  std::this_thread::sleep_for(std::chrono::seconds(1));27  std::cout << "Worker " << id << " finished." << std::endl;28}29 30void deadlock_func(std::unique_lock<std::mutex> &lock) {31  int i = 10;32  ++i;             // Set interrupt breakpoint here33  printf("%d", i); // Finish step-over from inner breakpoint34  auto func = [] { return ready_thread_id == 1; };35  cv.wait(lock, func);36}37 38int simulate_thread() {39  std::thread t1(worker, 1);40 41  std::unique_lock<std::mutex> lock(mtx);42  deadlock_func(lock); // Set breakpoint1 here43 44  std::thread t2(worker, 2); // Finish step-over from breakpoint145 46  cv.wait(lock, [] { return ready_thread_id == 2; });47 48  t1.join();49  t2.join();50 51  std::cout << "Main thread continues..." << std::endl;52 53  return 0;54}55 56int bar() { return 54; }57 58int foo(const std::string p1, int extra) { return p1.size() + extra; }59 60int main(int argc, char *argv[]) {61  std::string ss = "this is a string for testing",62              ls = "this is a long string for testing";63  foo(ss.size() % 2 == 0 ? ss : ls, bar()); // Set breakpoint2 here64 65  simulate_thread(); // Finish step-over from breakpoint266 67  return 0;68}69