#include #include #include #include #include #include #include int depth; thread_local int tlocal = 100; void bp1 (int t, int level, int n) { auto r = std::rand () % (t + level + n); std::this_thread::sleep_for (std::chrono::milliseconds (r)); printf ("bp1 in thread %d: %d\n", t, tlocal); } void bp2 (int t, int level, int n) { auto r = std::rand () % (t + level + n); std::this_thread::sleep_for (std::chrono::milliseconds (r)); printf ("bp2 in thread %d: %d\n", t, tlocal); } void sleeper (int t, int level, int n) { int loop = 0; if (++level < depth) sleeper (t, level, n); else while (true) { if (++loop % 2) bp1 (t, level, n); else bp2 (t, level, n); tlocal += t + 1; } } int main (int argc, char *argv[]) { auto max = argc > 1 ? std::atoi (argv[1]) : 8; depth = argc > 2 ? std::atoi (argv[2]) : 16; std::vector T; for (auto i = 0; i < max; i++) { auto t = new std::thread (sleeper, i, 0, 1000); pthread_setname_np (t->native_handle (), "worker"); T.push_back (t); } for (auto &t: T) t->join (); return 0; }