Reputation: 1329
i have a class say Graph
class Graph
{
bool* visited;
void myfun ()
{
visited = new bool[10];
for (int i=0;i<10;i++)
visited[i]=false;
myfunc2 ();
}
void myfunc2 ()
{
// Assume this changes the visited array
}
}
Now if i call the myfunc ()
in different threads then they would be working independtly and will change the visited array independetly.....this would make things go wrong.....
How do i deal with things like this while making a graph library of my own...?
Upvotes: 0
Views: 138
Reputation: 1354
If your threads has an own instance of "Graph", then you do not need thread safety because each thread accesses a different memory area.
But if you share the array between multiple threads:
Use locking (mutex, semaphore), synchronisation or inter-thread communication.
Lock the visited array, eg. std::lock, boost::mutex (or platform specific locking like pthread mutex). And try to lock the data, not the code.
somelock.lock();
visited[i]=false; //global array
somelock.unlock();
Upvotes: 1