美文网首页
pthread 线程同步

pthread 线程同步

作者: 幽客 | 来源:发表于2018-10-13 15:29 被阅读0次

    虽然本身是做Android开发的, 但经常会用到C/C++, 最近项目中刚好通过线程同步解决了一个问题,线程知识应用太广泛了, 所以在此记录下关于C/C++中比较实用基础知识, 本篇文章就说明一下pthread中线程同步的几种方式.

    pthread

    pthread 即 POSIX threads, POSIX表示可移植操作系统接口(Portable Operating System Interface of UNIX), 所以pthread就是在这个标准下实现的线程, 广泛用于类Unix操作系统上, 使用需要引入的头文件为 #include <pthread.h>基本使用示例代码如下:

    #include <stdio.h>
    #include <pthread.h>
    
    int count = 0;
    
    void* test_func_a(void* ptr);
    
    void main() {
        int loopCount = 5;
        pthread_t thread[5];
        char args[loopCount][10];
        for (int i = 0; i < loopCount; i++) {
            int err;
            sprintf(args[i], "Thread %d ", i);
            err = pthread_create(&thread[i], NULL, test_func_a, (void*) args[i]);
            if (err) {
                printf("create pthread failed ret:%d \n", err);
            }
        }
        for (int i = 0; i < loopCount; i++) {
            pthread_join(thread[i], NULL);
        }
    }
    
    void* test_func_a(void* ptr) {
        char* msg = (char*) ptr;
        count++;
        printf("%s value:%d \n", msg, count);
    }
    
    

    pthread创建很简单, 调用pthread_create()即可, 函数定义如下:

    int pthread_create(pthread_t * thread, 
                           const pthread_attr_t * attr,
                           void * (*start_routine)(void *), 
                           void *arg);
    

    参数1: 存储创建线程的id
    参数2:一些线程属性, 如果只是普通使用, 传NULL
    参数3: 函数指针, 即你要在此线程中运行的函数
    参数4:用于传递参数到运行的函数中

    注意:如果你是C/C++混合编程, 第三个参数在C++中只能传递全局函数或者类的静态函数, 不能传类的普通成员函数, 因为普通类成员函数是属于对象的, 类没有实例化是不能使用这个函数的.

    pthread_create()创建线程后, 线程会立即运行, 通过调用pthread_join()等待线程结束, 此函数会阻塞当前线程, pthread_join()成功返回后, 线程资源就会被释放, 上面的示例代码,编译(编译要加-pthread参数)运行后输出结果是不确定的, 原因是多个线程没有同步, 造成一些不可预料的结果发生, 其中某次输出结果如下:

     $ ./test_sync
    Thread 0  value:1
    Thread 2  value:3
    Thread 1  value:2
    Thread 3  value:4
    Thread 4  value:5
    

    下面开始讲线程同步的问题.

    线程同步-Joins

    pthread_join()大多数情况下都是用来结束线程的, 即退出程序释放相关线程, 但也可以作为简单同步功能来使用, 比如将上面示例代码修改为如下方式:

    #include <stdio.h>
    #include <pthread.h>
    
    
    int count = 0;
    
    void* test_func_a(void* ptr);
    
    void main() {
        int loopCount = 5;
        pthread_t thread[5];
        char args[loopCount][10];
        for (int i = 0; i < loopCount; i++) {
            int err;
            sprintf(args[i], "Thread %d ", i);
            err = pthread_create(&thread[i], NULL, test_func_a, (void*) args[i]);
            if (err) {
                printf("create pthread failed ret:%d \n", err);
            }
            //前一个线程结束后才运行下一个线程
            pthread_join(thread[i], NULL);
        }
        /*for (int i = 0; i < loopCount; i++) {
            pthread_join(thread[i], NULL);
        }*/
    }
    
    void* test_func_a(void* ptr) {
        char* msg = (char*) ptr;
        count++;
        printf("%s value:%d \n", msg, count);
    }
    

    这样修改后每次结果都是确定的, 原因是我们等前一个线程运行完成后,才启动下一个线程, 之前是一次性启动, 运行结果每次都是:

     $ ./test_join
    Thread 0  value:1
    Thread 1  value:2
    Thread 2  value:3
    Thread 3  value:4
    Thread 4  value:5
    

    此方式在时间项目中使用场景有限, 很少使用.

    线程同步-Mutexes

    Mutex即互斥量, 如果上锁后, 其他线程则无法获得锁导致线程阻塞, 直到锁被释放,才能再次获得锁进而执行相关代码, 示例代码:

    #include <stdio.h>
    #include <pthread.h>
    
    
    int count = 0;
    pthread_mutex_t mLock;
    
    void* test_func_a(void* ptr);
    
    void main() {
        int loopCount = 5;
        pthread_t thread[5];
        char args[loopCount][10];
        pthread_mutex_init(&mLock, NULL);
        for (int i = 0; i < loopCount; i++) {
            int err;
            sprintf(args[i], "Thread %d ", i);
            err = pthread_create(&thread[i], NULL, test_func_a, (void*) args[i]);
            if (err) {
                printf("create pthread failed ret:%d \n", err);
            }
        }
        for (int i = 0; i < loopCount; i++) {
            pthread_join(thread[i], NULL);
        }
        pthread_mutex_destroy(&mLock);
    }
    
    void* test_func_a(void* ptr) {
        pthread_mutex_lock(&mLock);
        char* msg = (char*) ptr;
        count++;
        printf("%s value:%d \n", msg, count);
        pthread_mutex_unlock(&mLock);
    }
    

    使用流程如下:
    1.定义 pthread_mutex_t pthread_mutex_t mLock;

    1. 初始化有两种方式, 调用pthread_mutex_init(&mLock, NULL);或者mLock = PTHREAD_MUTEX_INITIALIZER;效果一样, 后者是通过定义的宏来实现的.
    2. 调用lock和unlock函数, 上锁(获得锁)pthread_mutex_lock(&mLock);, 解锁(释放锁) pthread_mutex_unlock(&mLock);, 同一时间只有一个线程能获得该锁, 被lock后, 其他线程调用lock函数会阻塞当前线程.
    3. 释放定义的pthread_mutex_t 资源, 调用pthread_mutex_destroy(&mLock);

    上面代码运行结果如下:

     $ ./test_mutex
    Thread 0  value:1
    Thread 1  value:2
    Thread 2  value:3
    Thread 3  value:4
    Thread 4  value:5
    

    注意: 上面的例子只能保证value的值是按照预期从1变为5的, 但并不能保证thread的运行顺序,也就是说你运行的结果有可能是下面这样的:

     $ ./test_mutex
    Thread 0  value:1
    Thread 2  value:2
    Thread 1  value:3
    Thread 3  value:4
    Thread 4  value:5
    

    原因是上面的例子并不能保证各个线程获取锁的顺序, 因为每个线程获得锁的优先级是相同的, 所以顺序有可能每次都不一样.

    线程同步-Condition Variables

    Condition Variables 即条件变量, 在线程同步使用过程中要配合上面的mutex进行使用, 实际多线程开发使用较多, 比如经典的生产者-消费者关系就可以通过Condition Variables来实现, 常用的场景为满足某个条件让当前线程阻塞进行等待, 当其他线程满足另一个条件后, 通知正在等待的线程进行工作.
    下面通过一个简单例子来说明下基本使用:

    #include <stdio.h>
    #include <pthread.h>
    
    
    int count = 0;
    pthread_mutex_t mLock;
    pthread_cond_t mCond;
    
    void* test_func_a(void* ptr);
    
    void main() {
        int loopCount = 5;
        pthread_t thread[5];
        char args[loopCount][10];
        pthread_mutex_init(&mLock, NULL);
        pthread_cond_init(&mCond, NULL);
        for (int i = 0; i < loopCount; i++) {
            int err;
            sprintf(args[i], "Thread %d ", i);
            err = pthread_create(&thread[i], NULL, test_func_a, (void*) args[i]);
            if (err) {
                printf("create pthread failed ret:%d \n", err);
            }
        }
        printf("sleep 1s start \n");
        sleep(1);
        printf("sleep 1s end, call pthread_cond_signal() \n");
        pthread_mutex_lock(&mLock);
        //唤醒所有等待mCond的线程
        pthread_cond_broadcast(&mCond);
        //唤醒一个线程,如果当前有多个线程等待,
        //根据优先级和等待时间选择其中一个线程进行唤醒
        //pthread_cond_signal(&mCond);
        pthread_mutex_unlock(&mLock);
        for (int i = 0; i < loopCount; i++) {
            pthread_join(thread[i], NULL);
        }
        pthread_mutex_destroy(&mLock);
        pthread_cond_destroy(&mCond);
    }
    
    void* test_func_a(void* ptr) {
        pthread_mutex_lock(&mLock);
        pthread_cond_wait(&mCond, &mLock);
        pthread_mutex_unlock(&mLock);
        char* msg = (char*) ptr;
        count++;
        printf("%s value:%d \n", msg, count);
    }
    

    使用流程和mutex差不多,如下:

    1. 定义 pthread_cond_t pthread_cond_t mCond;
    2. 初始化也和mutex一样两种方式 pthread_cond_init(&mCond, NULL);mCond = PTHREAD_COND_INITIALIZER;
    3. 让当前线程阻塞进入等待状态
        pthread_mutex_lock(&mLock);
        pthread_cond_wait(&mCond, &mLock);
        pthread_mutex_unlock(&mLock);
    

    注意, 此处必须和mutex一起使用, 即调用pthread_cond_wait()这个函数本身要上锁, 否则会产生不可预料异常.

    1. 唤醒等待此条件变量的线程
        pthread_mutex_lock(&mLock);
        //唤醒所有等待mCond的线程
        pthread_cond_broadcast(&mCond);
        //唤醒一个线程,如果当前有多个线程等待,
        //根据优先级和等待时间选择其中一个线程进行唤醒
        //pthread_cond_signal(&mCond);
        pthread_mutex_unlock(&mLock);
    
    1. 释放资源 pthread_cond_destroy(&mCond);

    上面示例代码基本逻辑是启动五个线程, 默认开始就阻塞(等待mCond), 然后主线程sleep 1s后, 唤醒所有等待的线程, 此时5个线程会同时运行同一个函数, 输出结果不可预料, 某次结果如下:

     $ ./test_cond
    sleep 1s start
    sleep 1s end, call pthread_cond_signal()
    Thread 0  value:1
    Thread 3  value:4
    Thread 1  value:2
    Thread 2  value:3
    Thread 4  value:5
    

    总结

    根据我自己遇到的一些多线程问题, 我觉得多线程开发需要注意一下几点:

    1. 不要以常规思维思考没做过同步的一些代码的运行结果, 很多结果你自己是没法预料的.
    2. 写代码时思路要清晰, 有lock就要保证能在合适时机unlock, 不然很容易出现死锁.
    3. 线程参数传递大多数是通过指针来实现的, 需要注意这些参数的生命周期, C/C++和Java不同,
      Java中只要有引用对象就不会被释放, 但C/C++中则不同, 超出作用域或者手动释放, 相关资源都会变为不可用, 由于线程运行时间大多数不是立即运行的, 所以这种问题也比较常见.

    本文讲了三种线程同步方式 Joins, Mutexes和Condition Variables, 实际项目中后两个用的非常多, join更多的用在最后释放资源的时候用, 示例代码都是非常简单的基本使用方法, 还有很多高级用法没有说明, 有兴趣可自行查阅, 这里推荐一个非常不错的网站 http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

    相关文章

      网友评论

          本文标题:pthread 线程同步

          本文链接:https://www.haomeiwen.com/subject/npcoaftx.html