5

From what I understand, std::thread::swap swaps the thread ids of two threads. It doesn't change thread local storage or affect execution of either of the threads in any way. What is the purpose behind it? How/where/why is it used?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982

2 Answers2

3

Don't think of it as "swapping the thread IDs of two threads", think of it as swapping two thread variables:

std::thread a(...); // starts thread 1
std::thread b(...); // starts thread 2
a.swap(b); // or std::swap(a, b);
// now variable a points to thread 2
// and variable b points to thread 1

Most variables can be swapped with std::swap, even the ones that can't be copied. I'm not sure why they also created a swap member function for std::thread.

This is useful because you can, for example, sort a vector of threads. The sort algorithm will use swap to rearrange the threads in the vector. Remember that objects can't be moved in C++, only their contents. swap, and move semantics, allow you to move the contents of most objects into different objects. For thread, it moves the "pointer" to the thread.

user253751
  • 57,427
  • 7
  • 48
  • 90
  • See the [Copy and Swap idiom](https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom) for another case where this is useful. – user4581301 Feb 20 '20 at 18:41
  • _"... I'm not sure why they also created...."_ :Create a member function (needed because private state), specialise `std::swap` to use the member function. Now threads can be generially swapped using `std::swap` – Richard Critten Feb 20 '20 at 18:47
  • @RichardCritten Threads could be swapped using `std::swap` without the member function as well. The reason for the member function is that it can be more efficient than the generic `std::swap` would be. – eerorika Feb 20 '20 at 19:19
  • @RichardCritten `friend` exists and is generally used for this sort of thing. – user253751 Feb 20 '20 at 21:37
2

std::thread is internally referential type - similar to the way for example std::vector is. Internally, std::vector too simply refers to a memory buffer stored in dynamic memory.

What you describe is how swapping works with such types. Swapping a vector merely swaps pointers to the buffers (as well as some book keeping information) - none of the stored objects are affected by the operation. These pointers are "handles" to a resource. Similarly, swapping threads swaps the internal thread id - which is a handle to the thread resource - without affecting the state of the referred threads.

As for purpose of swapping... It's simply a useful thing to do. It is most notably used in sorting and other re-ordering algorithms. I don't know of a particular reason to re-order thread objects, but neither do I know of a reason why that shouldn't be possible.

eerorika
  • 232,697
  • 12
  • 197
  • 326