Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

C++ threading is quite similar to that of C, but allows for more flexibility. To be able to make threads, you must first include the thread header file, introduced in C++11, using

#include <thread>

thread t will make a thread t, with no function associated with it yet, meaning it will not run.

t(function) will then start it

To make a thread run from its creation, use

thread t(function)

 

to join a thread to the main thread, call

t.join()

 

t.joinable() returns whether or not the thread can be joined

 

t.detach() detaches the thread from the main thread.

 

One main difference from C threads is that we do not need to make a struct to store information for the thread, and can just pass the arguments into the thread directly, eg:
Image Added
Image Added

Another main difference in C++ threads is that not only functions can be passed into threads, but also member functions (methods) and objects.

 Image Added
In the picture above, operator is the object and publicFunction is the member function.

And here, we use them:
Image Added

To get a thread’s id, we can use get_id():
t.get_id()

 

We can also access four useful functions using the “this_thread” namespace.

this_thread::get_id returns the id of the current thread

this_thread::sleep_until makes the current thread sleep until reaching a certain time

this_thread::sleep_for makes the current thread sleep for a certain amount of time

this_thread::yield allows all other threads to run before the current one

 

To lock portions of a program, we can use mutex. We must include the mutex header and make a global mutex variable first. If we make one called “m”, we can use m.lock to call the mutex lock and m.unlock to unlock it.