linux 信号量

无名信号量

#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h>
    
sem_t sem;
    
void *func1(void *arg)
{
    sem_wait(&sem);
    int *running = (int *)arg;
    printf("thread func1 running : %d\n", *running);
    
    pthread_exit(NULL);
}
    
void *func2(void *arg)
{
    printf("thread func2 running.\n");
    sem_post(&sem);
    
    pthread_exit(NULL);
}
    
int main(void)
{
    int a = 3;
    sem_init(&sem, 0, 0);
    pthread_t thread_id[2];
    
    pthread_create(&thread_id[0], NULL, func1, (void *)&a);
    printf("main thread running.\n");
    sleep(10);
    pthread_create(&thread_id[1], NULL, func2, (void *)&a);
    printf("main thread still running.\n");
    pthread_join(thread_id[0], NULL);
    pthread_join(thread_id[1], NULL);
    sem_destroy(&sem);
    
    return 0;
}

命名信号量

#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h>
    
#define SEM_NAME " /sem_name"
    
sem_t *p_sem;
    
void *testThread(void *ptr)
{
    sem_wait(p_sem);
    sleep(2);
    pthread_exit(NULL);
}
    
int main(void)
{
    int i = 0;
    pthread_t pid;
    int sem_val = 0;
    p_sem = sem_open(SEM_NAME, O_CREAT, 0555, 5);
    
    if(p_sem == NULL)
    {
        printf("sem_open %s failed!\n", SEM_NAME);
        sem_unlink(SEM_NAME);
        return -1;
    }
    
    for(i = 0; i < 7; i++)
    {
        pthread_create(&pid, NULL, testThread, NULL);
        sleep(1);
        // pthread_join(pid, NULL);  // not needed, or loop
        sem_getvalue(p_sem, &sem_val);
        printf("semaphore value : %d\n", sem_val);
    }
    
    sem_close(p_sem);
    sem_unlink(SEM_NAME);
    
    return 0;
}
 

猜你喜欢

转载自www.cnblogs.com/nanqiang/p/11438722.html