阅读背景:

P-V操作(信号量的操作)

来源:互联网 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<pthread.h>
#include<semaphore.h>


char buf[60];
sem_t sem;
void *thread_fun(void *arg)
{
    while(1)
    {
        sem_wait(&sem);
        printf("you enter %d characters\n", strlen(buf)-1);
    }
}
int main()
{
    pthread_t thread;
    void *thread_result;
    if(0 > sem_init(&sem, 0, 0)) /* 初始化信号量 */
    {
        perror("sem_init");
        exit(-1);
    }
    if (0 > pthread_create(&thread, NULL, thread_fun, NULL)) /* 创建线程 */
    {
        perror("pthread_create");
        exit(-1);
    }
    printf("input 'quit' to exit\n");
    while(0 != (strncmp(buf, "quit", 4)))
    {
        fgets(buf, 60, stdin);
        sem_post(&sem);
    }


    return 0;
}#include<stdio.h>
#include<stdlib.h>
#include<s



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: