0

this code is to compute pi , written in c++ and is parallelized i have some problem in the mutex section in the code

#include <pthread.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <mutex>
using namespace std;

int thread_count ; 
double sum=0.0;
int n=100;


void* Thread_sum (void * rank)
{
  long myRank = (long) rank ;
  double factor , my_sum =0.0;
  long i ;
  long my_n = n / thread_count ;
  long my_first_i = my_n * myRank ; 
  long my_last_i = my_first_i + my_n ; 
   
  if(my_first_i % 2 == 0 ) factor = 1.0; 
  else factor = -1.0 ; 
  
  for (i= my_first_i ; i< my_last_i ; i++ , factor = -factor  )
  {
     pthread_mutex_lock(&mutex);
     sum += factor / (2*i+1);
     pthread_mutex_unlock(&mutex);
  }  
  return NULL;
}



int main(int argc , char * argv[] )
{
  
  long thread ;
  pthread_t* thread_handles ;
  
  pthread_mutex_t mutex;
  pthread_mutex_init(&mutex, NULL);
  
  
  thread_count = strtol(argv[1] , NULL , 10);
  
  thread_handles =(pthread_t*) malloc(thread_count * sizeof(pthread_t));
  
  for(thread = 0 ; thread<thread_count ; thread++ )
  {
     pthread_create (&thread_handles[thread] , NULL , Thread_sum , (void*)thread);
  }
  
  for(thread = 0 ; thread<thread_count ; thread++ )
  {
     pthread_join(thread_handles[thread] , NULL );
  }
  
  cout<<"the result of the pi is : "<<sum*4.0 <<endl;
  
  free(thread_handles);
  return 0;
}

when i compile this code , give me this two errors :

In function ‘void* Thread_sum(void*)’:
pimutex.cpp:27:31: error: expected primary-expression before ‘)’ token
   27 |      pthread_mutex_lock(&mutex);
      |                               ^
pimutex.cpp:29:33: error: expected primary-expression before ‘)’ token
   29 |      pthread_mutex_unlock(&mutex);
      |                                 ^

I searched on how i could solve this problem and i don't found a solution , can someone help ?!!!!! the problem is in the mutex , but idk what is it !!!

SimSim
  • 1
  • 2
    `mutex` is a local variable in the `main` function. Why should it be available in any other function? And there's barely any C++-specific code in your program, I recommend you invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) and learn C++ properly (lie learning to use [the `std::thread` class](https://en.cppreference.com/w/cpp/thread/thread)). – Some programmer dude Apr 08 '22 at 07:40
  • 1
    Your code is also not really parallelized. You have multiple threads, but the loops only run sequentially, becuase the acces to `sum` must be synchronized. I'd expect this to be much much slower than single-thread version. – Lukas-T Apr 08 '22 at 07:44

0 Answers0