您的位置:首页 > 编程语言 > C语言/C++

C语言信号量实现两线程循环打印

2013-08-03 21:19 260 查看
#include <stdio.h>
#include <pthread.h>
#include <error.h>
#include <sys/types.h>
#include <semaphore.h>
#include <stdlib.h>
sem_t sem1,sem2;
int number[10]={1,2,3,4,5,6,7,8,9,10};
int i=0;

void thread1(void)
{
do
{
sem_wait(&sem1);//等待sem1信号量
printf("thread1--->number[%d]=%d\n",i,number[i]);
i++;
sem_post(&sem2);//增加sem2信号量,使得thread2能够执行
}while(i<=9);
pthread_exit(NULL);
}
void thread2(void)
{
do
{
sem_wait(&sem2);
printf("thread2--->number[%d]=%d\n",i,number[i]);
i++;
sem_post(&sem1);
}while(i<=9);
pthread_exit(NULL);
}

int main()
{
int ret;
pthread_t a,b;
sem_init(&sem1,0,1);//初始化sem1为1,使thread1先执行
sem_init(&sem2,0,0);
ret=pthread_create(&a,NULL,(void *)thread1,NULL);
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
ret=pthread_create(&b,NULL,(void *)thread2,NULL);//返回值为0,创建成功
if(ret!=0)
{
printf ("Create pthread error!\n");
exit (1);
}
pthread_join(a,NULL);
pthread_join(b,NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐