0

I just started learning about thread today, and wanted to test the race condition of threads by running two codes with/without mutex.

#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>

#define NTHREADS 3
#define ITERATIONS (long long) 1000000000

//pthread_mutex_t mutex;

static long long counter = 0;

static void * thread_f(void * arg) {
    unsigned long long i;
    (void)arg;

    for (i = 0; i != ITERATIONS; i++) {
    //  pthread_mutex_lock(&mutex);
    counter = counter + 1;
    //  pthread_mutex_unlock(&mutex);
    }
 return NULL;

}

int main(void) {
    pthread_t threads[NTHREADS];

    int i;

    for (i = 0; i != NTHREADS; i++)
        pthread_create(&threads[i], NULL, thread_f, NULL);

    for (i = 0; i != NTHREADS; i++)
        pthread_join(threads[i], NULL);


    printf("expected = %lld, actual = %lld\n", NTHREADS*ITERATIONS, counter);
    printf("experienced %lld race conditions\n", NTHREADS*ITERATIONS - counter);


    system("pause");
    return 0;
}

So, without mutex, the program prints out these following lines on cmd:

expected = 3000000000, actual = 1174158414
experienced 1825841586 race conditions

However, if I put mutex in the code, and run the program, cmd pops up then shuts down itself without showing any result.

I want to know if I coded anything wrong or is misusing mutex lines as I really don't know much about threads.

p.s this is coded in windows 10, using visual studio

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tuto
  • 114
  • 6
  • Read this topic https://stackoverflow.com/questions/31663981/is-it-safe-to-call-pthread-mutex-lock-before-pthread-mutex-init. – rafix07 Dec 21 '18 at 08:17
  • (default) zero-initialization is not correct for `pthread_mutex_t` on all platforms (on Linux, careful design of the struct and its fields allows it to, but less well-designed systems like Apple's do not, I'm not sure about Windows). For portable static initialization, use `pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;`, as can be read in the manpage. – EOF Dec 21 '18 at 08:19
  • 1
    https://linux.die.net/man/3/pthread_mutex_init – rustyx Dec 21 '18 at 08:19
  • 1
    Can one of you make an answer or name a duplicate? – Yunnosch Dec 21 '18 at 08:21
  • 5
    Possible duplicate of [pthread mutex not working correctly](https://stackoverflow.com/questions/34936019/pthread-mutex-not-working-correctly) – EOF Dec 21 '18 at 08:25
  • your code works on Unix. I had to comment out `system("pause")` maybe because is specific of WIndows – roschach Dec 21 '18 at 08:54

1 Answers1

1

Thanks to EOF from the comment, I found out that I did not initialize mutex in the code.

I simply added:

if (pthread_mutex_init(&mutex, NULL)) {
    printf("Something went wrong\n");
    return 1;
}

this in the main, and everything works fine now.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tuto
  • 114
  • 6