zoukankan      html  css  js  c++  java
  • 线程同步技术

    线程共享进程的内存空间,打开的文件描述符,全局变量。
    当有多个线程同时访问一块内存空间或者一个变量、一个文件描述符,如果不加控制,那么可能会出现意想不到的结果。
     
    互斥(mutex)是相互排斥的意思,它是一种锁或者信号灯。
    互斥用来保护多个线程共享的数据和结构不会被同时修改,一个互斥锁只能有两个状态
      –locked---加锁
      –unlocked---解锁
    加锁后互斥不让其他线程访问。
    任何时刻只能有一个线程来掌握某个互斥上锁。
    一个线程如果试图在一个已经加锁的互斥上再加锁,这个线程会被挂起,直到加锁的线程释放掉互斥锁为止。
     
     

    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

    int pthread_mutex_lock(pthread_mutex_t *mutex);

    int pthread_mutex_unlock(pthread_mutex_t *mutex);

    PTHREAD_MUTEX_INITIALIZER是初始化一个快速锁的宏定义。
    pthread_mutex_lock用于给mutex加锁。
    pthread_mutex_unlock用于给mutex解锁。
     
     
    没有线程同步例子
    void *func(void *arg)
    {
        int *a = (int *)arg;
        printf("thread%d start
    ", *a);
        int i;
        for(i=0;i<10;i++)
        {
            printf("thread%d is running
    ", *a);
            sleep(1);
        }
        printf("thread%d end
    ", *a);
        pthread_exit(NULL);
    }
    int main(int arg, char * args[])
    {
        printf("process start
    ");
        pthread_t thr_d1, thr_d2;
        int i[2];
        i[0] = 1; i[1] =2;
        pthread_create(&thr_d1, NULL, func, &i[0]);
        pthread_create(&thr_d2, NULL, func, &i[1]);
        pthread_join(thr_d1, NULL);
        pthread_join(thr_d2, NULL);
        printf("process end
    ");
        return 0;
    }
    使用mutex线程同步例子
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    void *func(void *arg)
    {
        pthread_mutex_lock(&mutex);
        int *a = (int *)arg;
        printf("thread%d start
    ", *a);
        int i;
        for(i=0;i<10;i++)
        {
            printf("thread%d is running
    ", *a);
            sleep(1);
        }
        printf("thread%d end
    ", *a);
        pthread_mutex_unlock(&mutex);
        pthread_exit(NULL);
    }
    int main(int arg, char * args[])
    {
        printf("process start
    ");
        pthread_t thr_d1, thr_d2;
        int i[2];
        i[0] = 1; i[1] =2;
        pthread_create(&thr_d1, NULL, func, &i[0]);
        pthread_create(&thr_d2, NULL, func, &i[1]);
        pthread_join(thr_d1, NULL);
        pthread_join(thr_d2, NULL);
        printf("process end
    ");
        return 0;
    }
  • 相关阅读:
    Checking Types Against the Real World in TypeScript
    nexus pip proxy config
    go.rice 强大灵活的golang 静态资源嵌入包
    几个golang 静态资源嵌入包
    rpm 子包创建学习
    Rpm Creating Subpackages
    ava 类似jest snapshot 功能试用
    ava js 测试框架基本试用
    The Architectural Principles Behind Vrbo’s GraphQL Implementation
    graphql-compose graphql schema 生成工具集
  • 原文地址:https://www.cnblogs.com/shichuan/p/4496162.html
Copyright © 2011-2022 走看看