pthreads和quicksort

时间:2018-01-11 08:06:43

标签: c++ sorting pthreads

我正在尝试将一个简单的快速排序实现开始使用线程来提高性能,只是为了学习一些东西和乐趣。 由于我向pthread_create提供的参数,我在编译时遇到了一些麻烦。我不太清楚我在做什么。我实现线程atm的方式只是一个概念证明然后我将尝试使其更好任何关于如何更好地实现这一点的建议将不胜感激:D这里是我的代码..

#include <iostream>
#include <pthread.h>
#include <mutex>

#define MAX_THREADS 1 
int no_threads = 0;
std::mutex mtx;

struct arg_struct
{
    int * arr;
    int left;
    int right;
};

void *quicksort(arg_struct* arguments)
{
    int l = arguments->left, r = arguments->right;
    int tmp;
    int pivot = arguments->arr[(arguments->left + arguments->right)/2];

    /* partition */
    while(l <= r)
    {   
        //increment l untill arr[l] is larger than pivot 
        while (arguments->arr[l] < pivot)
            l++;
        //increment r untill arr[r] is less than pivot 
        while(arguments->arr[r] > pivot)
            r--;

        if(l <= r)
        {
            tmp = arguments->arr[l];
            arguments->arr[l] = arguments->arr[r];
            arguments->arr[r] = tmp;
            l++;
            r--;
        }
    }
    auto args = new arg_struct;
    args->left = arguments->left;
    args->right = r;
    args->arr = arguments->arr;

    if (arguments->left < r)

        mtx.lock(); 
        if(no_threads == 0)
        {
            pthread_t thread;
            int rc = pthread_create(&thread, NULL, &quicksort, args );   
            if(rc)
            {

            } 
        } 
        mtx.unlock();      
        if(no_threads == 1)
        {


            quicksort(args);

        } 
    if (l < arguments->right)
        quicksort(args);
}

int main(int argc, char ** argv)
{

    int arr[] = {55,5,6,2,4,6,2,4,534,5,4,2,1,1,3,5,634,7,87};

    arg_struct * arguments = new arg_struct; 
    arguments->arr = arr;
    arguments->left = 0;
    arguments->right =  sizeof(arr) / sizeof(arr[0]);
    quicksort(arguments);

    for(auto i = 0; i <= (int)sizeof(arr)/sizeof(arr[0])-1; i++)
    {
        std::cout << arr[i] << std::endl;
    } 

} 

和错误

threading.cpp:52:22: error: no matching function for call to 'pthread_create'
            int rc = pthread_create(&thread, NULL, &quicksort, args );   
                     ^~~~~~~~~~~~~~
/usr/include/pthread.h:234:12: note: candidate function not viable: no known conversion from 'void *(*)(arg_struct *)' to 'void *(*)(void *)' for 3rd argument
extern int pthread_create (pthread_t *__restrict __newthread,
           ^
1 error generated.

1 个答案:

答案 0 :(得分:1)

pthread_create()期望void* -> void*函数作为第三个参数,但您提供的quicksort具有签名arg_struct* -> void*。这是错误消息所说的内容:

no known conversion from 'void *(*)(arg_struct *)' to 'void *(*)(void *)' for 3rd argument

只需更改quicksort的签名:

void* quicksort(void* arg)
{
    arg_struct* arguments = reinterpret_cast<arg_struct*>(arg);
    // ...

现在,如果你使用一个相当新的编译器,C ++ 11提供了一种更便携,更简单的方法来管理线程:std::thread