并行快速排序中的升压互斥锁

boost mutex in parallel quicksort

本文关键字:快速排序 并行      更新时间:2023-10-16

这是我第一次使用互斥锁,所以我不太确定我在做什么,但我认为我有一个错误与使用向量容器的push_back函数的线程安全(我有多个线程写它在同一时间,并得到这个错误):* glibc检测到* ./quicksort: double free or corruption (out): 0x00007f2638000980 *

为了解决这个问题,我添加了一个互斥,但它似乎没有做任何事情,代码如下:

void parallel_quicksort(vector<int>& input)
{
    boost::mutex mutex;
    queue<pr_pair> partitions, temp_partitions;
    vector<pr_pair> jobs;
    parallel_partition(input, partitions, 0, input.size());
    pr_pair temp;
    while(1)
    {
        boost::thread_group threadpool;
        while(!partitions.empty())
        {
            temp = partitions.front();
            partitions.pop();
            jobs.push_back(temp);
            if (jobs.size() == NUM_THREADS)
            {
                for (int i = 0; i < NUM_THREADS; i++)
                {
                    temp = jobs.back();
                    jobs.pop_back();
                    threadpool.create_thread(boost::bind(&parallel_partition, boost::ref(input), boost::ref(temp_partitions), temp.p, temp.r));
                }
                threadpool.join_all();
            }
        }
        while(!jobs.empty())
        {
            temp = jobs.back();
            jobs.pop_back();
            threadpool.create_thread(boost::bind(&parallel_partition, boost::ref(input), boost::ref(temp_partitions), temp.p, temp.r));
        }
        threadpool.join_all();
        while(!temp_partitions.empty())
        {   
            temp = temp_partitions.front();
            partitions.push(temp);
            temp_partitions.pop();
        }   
        if(partitions.empty())
        {   
            break;
        }   
    }   
    return;
}
void parallel_partition(vector<int>& input, queue<pr_pair>& partitions, int p, int r)
{
    int p_store = p;
    int r_store = r;
    int pivot = input[r];
    while (p<r)
    {
        while (input[p] < pivot)
            p++;
        while (input[r] > pivot)
            r--;
        if (input[p] == input[r])
            p++;
        else if (p<r)
        {
            int tmp = input[p];
            input[p] = input[r];
            input[r] = tmp; }
    }
    pr_pair temp;
    if (r-1 > p_store)
    {
        boost::mutex::scoped_lock scoped_lock(mutex);
        temp.p = p_store;
        temp.r = r-1;
        partitions.push(temp);
    }
    if (r_store > r+1)
    {
        boost::mutex::scoped_lock scoped_lock(mutex);
        temp.p = r+1;
        temp.r = r_store;
        partitions.push(temp);
    }
    return;
}

快速扫描代码,您似乎保护了对分区数据结构的访问,但是您的输入数据结构也在parallel_partition方法中被修改了。这可能会导致问题