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
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Lesson 38: Threads (std::thread) | C++ Course lesson | BraveProgrammer
  1. Courses
  2. /
  3. C++ Course

Lesson 38 of 45

·C++

Lesson 38: Threads (std::thread)

12 min

Course progress84%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Launching a thread with callable objects
  • Joining and detaching threads
  • Thread safety concerns
  • Thread‑local storage

Threads (std::thread)

C++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.


Example: Launching a thread with a lambda

#include <thread>

void doWork(int id) {
    std::cout << \"Thread \" << id << \" is working\
\";
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    std::cout << \"Thread \" << id << \" finished\
\";
}

int main() {
    std::thread t1(doWork, 1);
    std::thread t2([](int id) {
        std::cout << \"Lambda thread \" << id << \" started\
\";
    }, 2);
    t1.join();
    t2.join();
    return 0;
}

Thread IDs and hardware concurrency

std::cout << \"Hardware threads: \" << std::thread::hardware_concurrency() << '\
';
std::thread t([]{ std::cout << \"Current thread id: \" << std::this_thread::get_id() << '\
'; });
 t.join();

Tip: Always join() or detach() a thread before its std::thread object is destroyed; otherwise the program terminates.


<Alert type="warning">Accessing shared data from multiple threads without synchronization leads to data races.

Make it stickPractice what you've learned1 quiz · 2 practical tests · Optional activities from C++ CourseBrowse activities
Previous lessonLesson 37: Move SemanticsContinue to lesson 39Lesson 39: Mutexes and Locks (std::mutex, std::lock_guard)Back to C++ Course curriculum