简体   繁体   English

如何使函数线程安全

[英]how to make the functions thread safe

i have a class say Graph 我上课说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..... 现在,如果我在不同的线程中调用myfunc () ,则它们将独立工作,并将独立更改访问的数组.....这将使事情出错.....

How do i deal with things like this while making a graph library of my own...? 在创建自己的图形库时如何处理此类问题?

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). std :: lock,boost :: mutex(或特定于平台的锁定,例如pthread互斥锁)。 And try to lock the data, not the code. 并尝试锁定数据,而不是代码。

somelock.lock();
visited[i]=false; //global array
somelock.unlock();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM