//
// Created by gxf on 2019/12/16.
//
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

void increase_num();

int sharedi=0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main(){
    pthread_t t1, t2, t3;
    pthread_create(&t1, NULL,increase_num, NULL);
    pthread_create(&t2, NULL,increase_num, NULL);
    pthread_create(&t3, NULL,increase_num, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    printf("shared:%d\n", sharedi);
    return 0;
}

void increase_num(){
    for (int i = 0; i < 100000; i++){
        if (pthread_mutex_lock(&mutex) != 0) {
            perror("mutex lock fail");
            exit(EXIT_FAILURE);
        }
        long temp = sharedi;
        temp += 1;
        sharedi = temp;
        if (pthread_mutex_unlock(&mutex)) {
            perror("mutex unlock fail");
            exit(EXIT_FAILURE);
        }
    }
}
12-22 01:17