0
void * bubbleSort(void * data){
  int * str;
  str = (int* ) data;
  int temp = 0;
    for ( int i = 0 ; i < len ; i++ ){
        for (int j = i + 1; j < len ; j++ ){
            if(str[i] > str[j]){
                temp = str[i];
                str[i] = str[j];
                str[j] = temp;
            }
        }
    }
}

int main(){
  int *data= new int[1000000];
  ...
  pthread_t thread[input];
   for ( int i = 0 ; i < input ; i ++){
     pthread_create(&thread[i],NULL,bubbleSort,arguments);  
     pthread_join(thread[i],NULL);
 }
}

I have int *data[1000000] and I want to use pthread to pass parameter to bubble sort.

The above is the code I wrote, but it is no output

How to successfully work ?

9
  • Can you explain in English what you are trying to do? How many threads do you want to spawn and what should each thread do? Commented May 5, 2020 at 11:10
  • @Botje I want to use pthread to execute bubble sort. I will key in a input by keyboard. No matter how many threads. Commented May 5, 2020 at 11:13
  • 1
    @Kia For the third and final time: what should each thread do? If each thread starts bubblesorting the full array you're going to run into horrible data races and corruption. Commented May 5, 2020 at 11:26
  • 1
    Note than int *data[10000]; is creating 10000 pointers to int. You have to drop the * to get an array of 10000 integers: int data[10000]; Commented May 5, 2020 at 11:30
  • 2
    Are you aware that this is a very hard problem? You will have to exchange values between threads with the appropriate synchronization and locking to ensure one thread doesn't start trashing another thread's part of the array. Commented May 5, 2020 at 11:41

1 Answer 1

1

To fix your immediate problem: your data variable is defined with the wrong type. int *data[1000] is an array of 1000 int *, which decays to int**. Your bubbleSort function expects an int *.

Declare data as follows instead:

int * data = new int[10000];

and then you can simply pass it to pthread_create as a void* like you do now.

However, modern C++ has a std::thread which is far easier to work with:

std::thread sorter(bubbleSort, data);
sorter.join();
Sign up to request clarification or add additional context in comments.

2 Comments

Oops, I didn't upload new int[1000]. Now I use std::thread sorter.... but it still no output
Edit your question into a minimal reproducible example. The version you posted is of course a no-op.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.