Chciałbym zsynchronizować dwie klasy, które posiadają wskaźnik na ten sam zasób.
- Czy mój kod jest poprawny?
- Czemu po zmianie
join
nadetach
program nie działa? - Czemu po dodaniu mutexa(skomentowany w kodzie) program się nie kompiluje?
class Foo
{
private:
bool free = true;
public:
bool isFree()
{
return free;
}
void setFree(bool free)
{
this->free = free;
}
};
class Owner
{
private:
std::shared_ptr<Foo> ptr;
//std::mutex mtx;
public:
Owner(std::shared_ptr<Foo> ptr) : ptr(ptr)
{
}
void run()
{
while (true)
{
//mtx.lock();
if (ptr->isFree())
{
ptr->setFree(false);
std::cout << "GIT\n";
Sleep(1000);
ptr->setFree(true);
}
//mtx.unlock();
}
}
};
int main()
{
Foo foo;
Owner o1 = Owner(std::make_shared<Foo>(foo));
Owner o2 = Owner(std::make_shared<Foo>(foo));
std::thread t1(&Owner::run, &o1);
std::thread t2(&Owner::run, &o2);
t1.join();
t2.join();
}
Cepo