[国嵌攻略][088][多线程同步]

线程同步

多个线程按照规定的顺序来执行,即为线程同步。

threadSync1.c

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t mutex;
int task = 0;

void *thread0();
void *thread1();

void main(){
    //创建互斥锁
    pthread_mutex_init(&mutex, NULL);
    
    //创建子线程
    pthread_t thread[2];
    
    pthread_create(&thread[0], NULL, thread0, NULL);
    pthread_create(&thread[1], NULL, thread1, NULL);
    
    //等待子线程
    pthread_join(thread[0], NULL);
    pthread_join(thread[1], NULL);
}

void *thread0(){
    //处理任务
    int i;
    
    for(i = 0; i < 10; i++){
        //获取互斥锁
        pthread_mutex_lock(&mutex);
        
        //处理任务
        task++;
        printf("thread0 task:%d
", task);
        
        //释放互斥锁
        pthread_mutex_unlock(&mutex);
        
        //睡眠等待
        sleep(1);
    }
    
    //退出线程
    pthread_exit(NULL);
}

void *thread1(){
    //获取互斥锁
    pthread_mutex_lock(&mutex);
    
    //查看任务
    while(task != 10){
        //释放互斥锁
        pthread_mutex_unlock(&mutex);
        
        //睡眠等待
        sleep(1);
        
        //获取互斥锁
        pthread_mutex_lock(&mutex);
    }
    
    //处理任务
    task++;
    printf("thread1 task:%d
", task);
    
    //释放互斥锁
    pthread_mutex_unlock(&mutex);

    //退出线程
    pthread_exit(NULL);
}

threadSync2.c

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

pthread_mutex_t mutex;                            //互斥锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;   //条件变量
int task = 0;

void *thread0();
void *thread1();

void main(){
    //创建互斥锁
    pthread_mutex_init(&mutex, NULL);
    
    //创建子线程
    pthread_t thread[2];
    
    pthread_create(&thread[0], NULL, thread0, NULL);
    pthread_create(&thread[1], NULL, thread1, NULL);
    
    //等待子线程
    pthread_join(thread[0], NULL);
    pthread_join(thread[1], NULL);
}

void *thread0(){
    //处理任务
    int i;
    
    for(i = 0; i < 10; i++){
        //获取互斥锁
        pthread_mutex_lock(&mutex);
        
        //处理任务
        task++;
        printf("thread0 task:%d
", task);
        
        //释放互斥锁
        pthread_mutex_unlock(&mutex);
        
        //睡眠等待
        sleep(1);
    }
    
    //条件通知
    pthread_cond_signal(&cond);
    
    //退出线程
    pthread_exit(NULL);
}

void *thread1(){
    //获取互斥锁
    pthread_mutex_lock(&mutex);
    
    //条件等待
    if(task != 10){
        pthread_cond_wait(&cond, &mutex);   //条件等待时会自动解锁,然后睡眠等待,获得条件通知再自动加锁
    }
    
    //处理任务
    task++;
    printf("thread1 task:%d
", task);
    
    //释放互斥锁
    pthread_mutex_unlock(&mutex);

    //退出线程
    pthread_exit(NULL);
}
原文地址:https://www.cnblogs.com/d442130165/p/5229869.html