2

I have a program to count factorial, but it works uncorrect. I should change it using Mutex, but I don't understand this feature.

// POSIX Threads, example #5-1
#include <iostream>
#include <pthread.h>

using namespace std;

void* fact(void *data) {
  int arg = *(int*)data;
  cout << arg << endl;
  static int res = 1;
  for(int i=2; i<=arg; i++) res*=i;
  return &res;
}

int main() {
  const int NMAX = 5;
  pthread_t tid[NMAX];
  int n, i;
  for(i=0; i<NMAX; i++) {
    n = i + 1;
    pthread_create(&tid[i], NULL, fact, &n);
  }

  for(i=0; i<NMAX; i++) {
    int* p_res;
    pthread_join(tid[i], (void**)&p_res);
    cout << "n = " << i+1
     << ", res = " << *p_res << endl;
  }

  return 0;
}

I can change it using loop.

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

using namespace std;

void* fact(void *data) {
    int arg = *(int*)data;
    int res = 1;
    for(int i = 2; i <= arg; i++) res *= i;
    *(int*)data = res;
    return NULL;
}

int main() {
    const int NMAX = 5;
    pthread_t tid[NMAX];
    int i, data[NMAX];
    for(i = 0; i < NMAX; i++) {
        data[i] = i + 1;
        pthread_create(&tid[i], NULL, fact, &data[i]);

    }

    for(i = 0; i < NMAX; i++) {
        pthread_join(tid[i], NULL);
        cout << "n = " << i + 1 << ", res = " << data[i] << endl;
    }

    return 0;
}

But I have no idea with using Mutex. I don't know what way to use it and can't understand how does it work.

NineWasps
  • 2,081
  • 8
  • 28
  • 45
  • off topic: consider using [std::thread](http://en.cppreference.com/w/cpp/thread/thread) and [std::mutex](http://en.cppreference.com/w/cpp/thread/mutex) in place of the POSIX calls. – user4581301 May 12 '16 at 23:11
  • On topic: Mutex creates a creates a region of code that only one thread can enter at a time. In your case this would be... I'm not sure. Unfortunately what you are doing doesn't make much sense to me. – user4581301 May 12 '16 at 23:12
  • It works uncorrect and I should change it with `mutex` – NineWasps May 13 '16 at 09:08
  • Recommend making a program that works correctly with one thread first. Once you have an algorithm that does what you want you'll be in much better position to make decisions on how to split up up among many threads and be able to define regions that need mutex--or some other type--protection. Calculating a factorial might only need a [`std::atomic`](http://en.cppreference.com/w/cpp/atomic/atomic) to hold the result. Also note that an `int` can't hold a very big factorial before overflowing, certainly not a big enough factorial (20! for a 64-bit `int`) to require multithreading to compute. – user4581301 May 13 '16 at 15:07

0 Answers0