8.线程同步-信号量、条件变量

55 阅读1分钟

信号量

#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <semaphore.h>

using namespace std;

int var=0;

//线程同步-信号量
sem_t sem;     

void *thmain(void *arg);    //线程主函数

int main()
{
    sem_init(&sem, 0, 1);
    pthread_t thid1=0, thid2=0;
    if(pthread_create(&thid1, NULL, thmain, NULL) != 0) {printf("thid1 faile\n"); exit(-1);}
    if(pthread_create(&thid2, NULL, thmain, NULL) != 0) {printf("thid2 faile\n"); exit(-1);}

    //等待子线程退出
    printf("join...\n");
    pthread_join(thid1, NULL);
    pthread_join(thid2, NULL);
    printf("join ok.\n");

    printf("var=%d\n", var);

    sem_destroy(&sem);      //主进程退出的时候销毁信号量
    return 0;
}

void *thmain( void *arg)
{
    for(int i=0; i <100000; i++)
    {
        sem_wait(&sem);
        var++;
        sem_post(&sem);
    }
}

条件变量

#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <iostream>
#include <signal.h>

using namespace std;

int var=0;
//线程同步-条件变量
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //声明条件变量并初始化
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;    //声明互斥锁并初始化

void *thmain(void *arg);    //线程主函数

void handle(int sig);       //信号15的处理函数

int main()
{
    signal(15, handle);     //设置信号15的处理函数

    pthread_t thid1=0, thid2=0, thid3=0;
    if(pthread_create(&thid1, NULL, thmain, NULL) != 0) {printf("thid1 faile\n"); exit(-1);}
    if(pthread_create(&thid2, NULL, thmain, NULL) != 0) {printf("thid2 faile\n"); exit(-1);}
    if(pthread_create(&thid3, NULL, thmain, NULL) != 0) {printf("thid3 faile\n"); exit(-1);}

    //等待子线程退出
    printf("join...\n");
    pthread_join(thid1, NULL);
    pthread_join(thid2, NULL);
    pthread_join(thid3, NULL);
    printf("join ok.\n");

    pthread_cond_destroy(&cond);      //主进程退出的时候销毁锁
    return 0;
}

void *thmain( void *arg)
{
    while(true)
    {
        printf("线程%lu开始等待条件信号...\n", pthread_self());
        pthread_cond_wait(&cond, &mutex);       //等待条件信号
        printf("线程%lu开始等待条件信号成功\n", pthread_self());
    }
}

void handle(int sig)
{
    printf("发送条件信号...\n");
    //pthread_cond_signal(&cond);     //唤醒等待条件变量的一个线程
    pthread_cond_broadcast(&cond);    //唤醒等待条件变量的全部线程
}