信号量

有几个线程就有几个除互斥信号之外的信号量,每个线程等待自己的信号量有位置,

并最后给其他信号量位置。初始时,生产者的值非0,消费者的值为0。

/*
        #include <semaphore.h>

        int sem_init(sem_t *sem, int pshared, unsigned int value);
            参数:
                sem:信号量
                pshared:0用在线程,非0用在进程
                value:信号量中的值


        int sem_destroy(sem_t *sem);
            释放资源

        int sem_wait(sem_t *sem);
            信号量-1,为0时阻塞线程

        int sem_trywait(sem_t *sem);
            信号量-1,为0立即返回
        int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

        int sem_post(sem_t *sem);
            信号量+1
        int sem_getvalue(sem_t *sem, int *sval);  
            获取信号量的值
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>

pthread_cond_t cond;



struct Node
{
    int num;
    struct Node* next;
};

struct Node *head = NULL;
pthread_mutex_t mutex;
sem_t proid, cusid;

void *producer(void *arg)
{   

    while(1)
    {
        sem_wait(&proid);
        pthread_mutex_lock(&mutex);
        struct Node* node = (struct Node*) malloc(sizeof(struct Node));
        node->num = rand() % 1000;
        node->next = head;
        head = node;
        printf("add node, num: %d, tid: %ld\n", node->num, pthread_self());
        usleep(100);
        pthread_mutex_unlock(&mutex);
        sem_post(&cusid);
    }
    return NULL;
}

void *customer(void *arg)
{
    while(1)
    {
        sem_wait(&cusid);
        pthread_mutex_lock(&mutex);

        struct Node* node = head;
        head = head->next;

        printf("delete node, num: %d, tid: %ld\n", node->num, pthread_self());
        free(node);
        usleep(100);
        pthread_mutex_unlock(&mutex);
        sem_post(&proid);
    }
    return NULL;
}






int main()
{
    sem_init(&proid, 0, 8);
    sem_init(&cusid, 0, 0);

    pthread_mutex_init(&mutex, NULL);


    pthread_t ptids[5], ctids[5];

    for(int i = 0; i < 5; i++)
    {
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }


    for(int i = 0; i < 5; i++)
    {
        pthread_detach(ptids[i]);  // pthread_join是阻塞的,所以多个线程最好用detach
        pthread_detach(ctids[i]);
    }


    while(1)
    {
        sleep(10);
    }


    pthread_mutex_destroy(&mutex);




    pthread_exit(NULL);

    return 0;
}

 

posted @ 2023-05-07 09:29  WTSRUVF  阅读(14)  评论(0编辑  收藏  举报