Reputation: 5
I am trying to turn a simple quicksort implementation to start using threads for performance, simply just to learn some stuff and for fun. I am having a bit of trouble compiling because of the arguments I am supplying to pthread_create. I am not quite sure what I am doing. the way i am implementing threads atm was just a proof of concept then I was going to try and make it better any suggestions on how to better acheive this would be greatly appreciated :D here is my code..
#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;
}
}
and the errors
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.
Upvotes: 0
Views: 614
Reputation: 40080
pthread_create()
expects a void* -> void*
function as third argument, but you provide quicksort
which has signature arg_struct* -> void*
. This is what the error message says:
no known conversion from 'void *(*)(arg_struct *)' to 'void *(*)(void *)' for 3rd argument
Simply change quicksort
's signature:
void* quicksort(void* arg)
{
arg_struct* arguments = reinterpret_cast<arg_struct*>(arg);
// ...
Now, if you use a decently recent compiler, C++11 provides a more portable and easier way to manage thread: std::thread
.
Upvotes: 1