confide

导航

unix编程——信号量

线程间同步:

生产者与消费者问题,分别为一个线程执行生产消费,信号量则在进程空间中共享。

sem.c:

#include <stdio.h>
#include
<stdlib.h>
#include
<semaphore.h>
#include
<sys/stat.h>
#include
<unistd.h>
#include
<fcntl.h>

sem_t
*put;
sem_t
*get;

int nitems;
int curr;
void*producer()
{
while(1){
sem_wait(put);
if(curr > nitems){
sem_post(
get);
return;
}
printf(
"p %d\n",curr);
curr
++;

sem_post(
get);
sleep(
1);
}
}

void*consumer()
{
int i;
for(i =1; i <= nitems; i++){
while(1){
sem_wait(
get);
if(i < curr){
sem_post(put);
break;
}
sem_post(put);

}
printf(
"c %d\n",i);
}

}
int main()
{
pthread_t th_prod;
pthread_t th_cosm;
int i,j;
nitems
=10;
curr
=1;
put
= sem_open("\\temp.1",O_CREAT | O_EXCL,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH,1);
get= sem_open("\\temp.2",O_CREAT | O_EXCL,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH,0);
pthread_create(
&th_prod,NULL,producer,NULL);
pthread_create(
&th_cosm,NULL,consumer,NULL);
pthread_join(th_prod,NULL);
sem_unlink(
"\\temp.1");
sem_unlink(
"\\temp.2");
exit(
0);
}

执行命令:

gcc -o sem sem.c -pthread

执行结果:

View Code
p 1
c
1
p
2
c
2
p
3
c
3
p
4
c
4
p
5
c
5
p
6
c
6
p
7
c
7
p
8
c
8
p
9
c
9
p
10
c
10

posted on 2011-08-15 16:00  confide  阅读(360)  评论(0)    收藏  举报