我的函数是线程安全的和可重入的吗?

Is my function thread-safe and reentrant?

我有一个由两个线程调用的函数,每个线程都有一个向量的本地副本。我的假设是,由于每个线程都有不同的向量,因此下面的函数是线程安全的。
下面的函数是线程安全的和可重入的吗?

int Partition(int high, int low, int pivot, std::vector<int>& arr)
{
    int j = low;
    for (int i = low ; i <= high ; i++)
    {
        if (arr[i] <= pivot)
        {

            swap(i , j++ , arr);

        }
    }
    return arr.size() - j;
}

void swap(int fromIndex , int toIndex , std::vector<int> &arr)
{
    arr[fromIndex] = arr[fromIndex]^arr[toIndex];
    arr[toIndex] = arr[fromIndex]^arr[toIndex];
    arr[fromIndex] = arr[fromIndex]^arr[toIndex];
}

如果函数更改线程实例之间的共享内存,则该函数不是线程安全的。如果你有两个不同的对象(不是指针)指向向量,那么你不必担心。

如果你想让它成为线程安全的,你可以使用互斥锁:

#include <thread>         // std::thread
#include <mutex>          // std::mutex

std::mutex mtx;           // mutex for critical section

int Partition(int high, int low, int pivot, std::vector<int>& arr)
{
    int j = low;
    for (int i = low ; i <= high ; i++)
    {
        if (arr[i] <= pivot)
        {
            mtx.lock();
            swap(i , j++ , arr);
            mtx.unlock();
        }
    }
    return arr.size() - j;
}

可以找到有关互斥锁的更多信息here

函数本身不是线程安全的,因为可以从不同的线程向它传递相同的向量。

但是,如果您在这些函数之外进行同步,则可以使用非线程安全函数编写线程安全代码。 IE。如果您的调用代码注意绝不会同时将同一个向量传递给该函数,那么 调用代码 将是线程安全的。

关于重入,Wikipedia有以下说法:

In computing, a computer program or subroutine is called reentrant if it can be interrupted in the middle of its execution and then safely called again ("re-entered") before its previous invocations complete execution. The interruption could be caused by an internal action such as a jump or call, or by an external action such as a hardware interrupt or signal. Once the reentered invocation completes, the previous invocations will resume correct execution.

我强调了该定义的最后一部分,因为很明显,非线程安全的函数可能无法正确执行,因此无法通过该定义重入。