现在的位置: 首页 > 综合 > 正文

1.7 线程同步–信号量

2014年02月15日 ⁄ 综合 ⁄ 共 1244字 ⁄ 字号 评论关闭

目录

一.函数:

1.信号量的初始化与销毁:
#include <semaphore.h>
int sem_init (set_t *sem, int pshared, unsigned int value);
int sem_destroy (sem_t * sem);
value:参数指定信号量的初始值。
pshared:为 0,信号量将被进程内的线程共享;非0,信号量将在进程之间共享(linux暂不支持)。
Both return:0 on success; on error, -1 is returned, and errno is set to indicate the error.
2.信号量的加减:
#include <semaphore.h>
int sem_post( set_t *sem);    //给信号量的值加1。
int sem_wait( set_t *sem);    //给一个信号量减1,永远等待信号量的值不为零才执行这个动作。
int sem_trywait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

Both return:0 on success; on error, the value of the semaphore is left unchanged, -1 is returned,
            and errno is set to indicate the error.
二.重点
三.例子:

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

sem_t gsem;
char gbuf[1024];

void * thread_func (void *arg)
{
    sem_wait(&gsem);
    while(strncmp("EOF",gbuf,3) != 0)
    {
        printf("you input:%s\n",gbuf);
        sem_wait(&gsem);
    }
    pthread_exit(NULL);
}

int main()
{
    int ret;
    pthread_t tid;
    void *tret;

    ret=sem_init(&gsem,0,0);
    if (ret != 0)
        printf("sem init error:%s\n",strerror(ret));

    pthread_create(&tid,NULL,thread_func,NULL);

    while(strncmp("EOF",gbuf,3) != 0)
    {
        fgets(gbuf,1024,stdin);
        sem_post(&gsem);
    }
    pthread_join(tid,&tret);

    printf("end\n");
    sem_destroy(&gsem);
    return 0;
}

运行:
root@ubuntu1:~/11# ./a.out
123
you input:123

qweasd
you input:qweasd

EOF
end
root@ubuntu1:~/11#

抱歉!评论已关闭.