mercredi 23 août 2023

Can I use a friend function definied within a class as my thread function

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 this article 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 enter image description here

Thank you

I have tried referring to the article, and couple of other materials in Tutorials Point and GeekforGeeks

Aucun commentaire:

Enregistrer un commentaire