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;
    }
  • 相关阅读:
    这年头学爬虫还就得会点 scrapy 框架
    【全栈之路】JAVA基础课程十_JAVA虚拟机(20190706v1.1)
    牛客练习赛61
    ERD图
    深入理解Java虚拟机-如何利用VisualVM对高并发项目进行性能分析
    阿里研究员吴翰清:世界需要什么样的智能系统?
    《深入理解 C# (第2版)》
    HtmlAgility 抓取网页上的数据
    abp(net core)+easyui+efcore实现仓储管理系统——入库管理之三存储过程(三十九)
    如何Tomcat完美访问web项目,无需配置“项目名”
  • 原文地址:https://www.cnblogs.com/shichuan/p/4496162.html
Copyright © 2011-2022 走看看