zoukankan      html  css  js  c++  java
  • 多线程同步之互斥量

        谈到多线程编程,同步是一定要讲的。给个例子:

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    int count = 0;
    #define N 100000
    void* fun()
    {
        int i;
        for (i = 0; i < N; ++i)
        {
            int tmp = count;
            tmp++;
            count = tmp;
        }
    }
    
    int main()
    {
        pthread_t tid1, tid2;
        int ret1, ret2;
        ret1 = pthread_create(&tid1, NULL, fun, NULL);
        ret2 = pthread_create(&tid2, NULL, fun, NULL);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
        printf("count = %d
    ", count);
        return 0;
    }
    View Code

        两个线程同时对一个数据执行自增操作,结果是多少呢?

        可以看出,每次执行的结果都是不一样的。而且,都不是我们所希望的200000。主要原因是程序里的自增操作不是原子操作,两个线程由于CPU的调度,会交错执行。

    接下来,我们通过互斥量来实现两个线程的同步。

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    int count = 0;
    #define N 100000
    pthread_mutex_t mutex;
    void* fun()
    {
        int i;
        for (i = 0; i < N; ++i)
        {
            pthread_mutex_lock(&mutex);
            int tmp = count;
            tmp++;
            count = tmp;
            pthread_mutex_unlock(&mutex);
        }
    }
    
    int main()
    {
        pthread_mutex_init(&mutex, NULL);
    
        pthread_t tid1, tid2;
        int ret1, ret2;
        ret1 = pthread_create(&tid1, NULL, fun, NULL);
        ret2 = pthread_create(&tid2, NULL, fun, NULL);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);
        printf("count = %d
    ", count);
    
        pthread_mutex_destroy(&mutex);
        return 0;
    }
    View Code

        在自增操作前后,通过成对的加锁解锁操作,使得自增操作成为一个原子操作,从而达到线程同步。

    用到的函数:

    // 成功返回0
    int pthread_mutex_init(pthread_mutex_t *mutex, 
        const pthread_mutexattr_t *attr);
    int pthread_mutex_destroy(pthread_mutex_t *mutex);
    int pthread_mutex_lock(pthread_mutex_t *mutex);
    int pthread_mutex_unlock(pthread_mutex_t *mutex);
  • 相关阅读:
    [转]实习生需要懂的40大基本规矩
    [转]Linux下pppoe配合Drcom插件上网方法介绍......
    收藏一些图书
    [转]30个自我提升技巧
    [转]关于Gmail打不开的解决办法
    [转]李开复经典语录盘点:人生之路在于每次的选择
    [转]哈佛管理世界中智慧
    胡伟武校友在2011年中国科大本科生毕业典礼暨学位授予仪式上的讲话
    Dynamics4.0和Dynamics2011处理Email的方法
    JS实现简单的ToolTip功能
  • 原文地址:https://www.cnblogs.com/gattaca/p/4729920.html
Copyright © 2011-2022 走看看