c多线程不加锁demo

江枫思渺然 提交于 2019-12-13 01:10:32
//
// Created by gxf on 2019/12/13.
//
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int shareInt = 0;
void increase_num(void);

int main() {
    int ret;
    pthread_t thread1, thread2, thread3;

    ret = pthread_create(&thread1, NULL, increase_num, NULL);
    ret = pthread_create(&thread2, NULL, increase_num, NULL);
    ret = pthread_create(&thread3, NULL, increase_num, NULL);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);

    printf("sharedInt:%d\n", shareInt);

    return 0;
}

void increase_num(void) {
    long i, tmp;
    for (i=0; i <= 100000; i++) {
        tmp = shareInt;
        tmp = tmp + 1;
        shareInt = tmp;
    }
}

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!