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;
    }
  • 相关阅读:
    字节流 数据报 原始套接字
    付宝研究员王益:“对我影响最大的三本编程书”
    e^π和π^e谁大的问题
    https://stackoverflow.com/questions/3232943/update-value-of-a-nested-dictionary-of-varying-depth
    计算机 人造学科
    位域 内存对齐
    LeetCode上并发题目无Go版本:台湾同胞试水 — 交替打印FooBar
    a
    Hash-based .pyc Files
    Most basic operations in Go are not synchronized. In other words, they are not concurrency-safe.
  • 原文地址:https://www.cnblogs.com/shichuan/p/4496162.html
Copyright © 2011-2022 走看看