Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. C++ Course

Lesson 32 of 45 · C++

Lesson 38: Threads (std::thread)

Duration: 12 min

Threads (std::thread)\n\nC++11 introduced native threading support via the <thread> library. A std::thread represents a single thread of execution. You can start a thread with any callable object: a function pointer, lambda, functor, or member function.\n\n---\n\n## Example: Launching a thread with a lambda\ncpp\n#include <thread>\n\nvoid doWork(int id) {\n std::cout << \"Thread \" << id << \" is working\\n\";\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n std::cout << \"Thread \" << id << \" finished\\n\";\n}\n\nint main() {\n std::thread t1(doWork, 1);\n std::thread t2([](int id) {\n std::cout << \"Lambda thread \" << id << \" started\\n\";\n }, 2);\n t1.join();\n t2.join();\n return 0;\n}\n\n\n## Thread IDs and hardware concurrency\ncpp\nstd::cout << \"Hardware threads: \" << std::thread::hardware_concurrency() << '\\n';\nstd::thread t([]{ std::cout << \"Current thread id: \" << std::this_thread::get_id() << '\\n'; });\n t.join();\n\n\n> Tip: Always join() or detach() a thread before its std::thread object is destroyed; otherwise the program terminates.\n\n---\n\n<Alert type="warning">Accessing shared data from multiple threads without synchronization leads to data races.

Previous: Lesson 37: Move SemanticsNext: Lesson 39: Mutexes and Locks (std::mutex, std::lock_guard)