【问题标题】:boost mutex in parallel quicksort在并行快速排序中提升互斥锁
【发布时间】:2014-05-08 21:22:05
【问题描述】:

这是我第一次使用互斥锁,所以我不太确定自己在做什么,但我认为使用向量容器的 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;
}

【问题讨论】:

    标签: c++ boost quicksort boost-thread boost-mutex


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-09
      • 2013-08-09
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      相关资源
      最近更新 更多