您的位置:首页 > 其它

信号量(稍微有点线程知识)(生产者消费者)

2013-07-31 20:45 141 查看
新学的信号量,自己写的生产者消费者:

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

#define N 10

sem_t w;

sem_t p;

int in1 = 0;

int in2 = 0;

int in = 0;

int out = 0;

int a
= {0};

void Pro()

{

while(1)

{

sleep(1);

sem_wait(&w);

a[in] = in % N;

printf("Product :%d\n",a[in]);

in++;

sem_post(&w);

sem_post(&p);

}

}

void Cus()

{

while(1)

{

sem_wait(&p);

sem_wait(&w);

a[out] = out % N;

printf("Custer :%d\n",a[out]);

out++;

sem_post(&w);

}

}

int main()

{

pthread_t thread_id1;

pthread_t thread_id2;

in1 = sem_init(&w,0,1);

in2 = sem_init(&p,0,0);

pthread_create(&thread_id1,NULL,(void *)&Pro,NULL);

pthread_create(&thread_id2,NULL,(void *)&Cus,NULL);

pthread_join(thread_id1,NULL);

pthread_join(thread_id2,NULL);

return 0;

}

新手,大神们给些意见!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐