Can I use a friend function defined within a class as my thread function?

73 views Asked by At

I'm new to C++ and trying to understand concepts in threads. My reading material surrounding this question is "Anthony Williams - C++ Concurrency in Action" - Listing 3.6.

I have written the listing by myself, but can't seems to get the code to work. I believe the problem I'm facing is calling an in-class friend function as the thread function. I have referred to Interaction between c++11 std::thread and class friend function as well.

Here is my code:

#include <iostream>
#include <mutex>
#include <thread>

class some_big_object
{
};
void swap(some_big_object &lhs, some_big_object &rhs);

class X
{
private:
    some_big_object some_detail;
    std::mutex m;

public:
    X(some_big_object const &sd) : some_detail(sd) {}
    friend void swap(X &lhs, X &rhs)
    {
        if (&lhs == &rhs)
        {
            return;
        }
        std::lock(lhs.m, rhs.m);
        std::lock_guard<std::mutex> lock_a(lhs.m, std::adopt_lock);
        std::lock_guard<std::mutex> lock_b(rhs.m, std::adopt_lock);
        swap(lhs.some_detail, rhs.some_detail);
    }
};

int main(void)
{
    some_big_object s1;
    some_big_object s2;
    X a(s1);
    X b(s2);
    std::thread t1(swap(a, b));
    t1.join();

    return 0;
}

Compilation error:

image

I have tried referring to Interaction between c++11 std::thread and class friend function, and a couple of other materials in Tutorials Point and GeekforGeeks.

0

There are 0 answers