#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

 

int sharedi = 0;

void increse_num(void);

pthread_mutex_t mutex;//互斥锁定义

int main(){

    int ret;

    pthread_t thrd1, thrd2, thrd3;

    pthread_mutex_init(&mutex,NULL);//互斥锁初始化一般放在线程创立之前

 

ret = pthread_create(&thrd1, NULL, (void *)increse_num, NULL);

ret = pthread_create(&thrd2, NULL, (void *)increse_num, NULL);

    ret = pthread_create(&thrd3, NULL, (void *)increse_num, NULL);

 

    pthread_join(thrd1, NULL);

    pthread_join(thrd2, NULL);

    pthread_join(thrd3, NULL);

    pthread_mutex_destroy(&mutex);//互斥锁销毁

    printf("sharedi = %d\n", sharedi);

 

    return 0;

 

}

void increse_num(void) {

    long i,tmp;

    for(i=0; i<=3000000; i++) //当运行很大的数据时不用互斥锁,极容易出错

{

    pthread_mutex_lock(&mutex);//加锁

        tmp = sharedi;

        tmp = tmp + 1;

        sharedi = tmp;

    pthread_mutex_unlock(&mutex);//解锁    加锁与解锁过程中相当于是原子操作不会由于cpu时间片而中断中间的每

 

一步操作

    }

}

posted on 2022-03-15 20:12  down^to^earth  阅读(87)  评论(0)    收藏  举报