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

linux信号量

2013年10月19日 ⁄ 综合 ⁄ 共 612字 ⁄ 字号 评论关闭
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem;

void * thread_function1(void * args)
{
	while(1){
		printf("function1 wait\n");
		sem_wait(&sem);
		printf("function1 run\n");

	}
}

void * thread_function2(void * param)
{
	while(1){
		printf("function2 run\n");
		sem_post(&sem);
		sleep(5);
	}
}

int main(void)
{
	pthread_t pthread;
	int ret;

	ret = sem_init(&sem,0,0);
	if(ret != 0 ){
		printf("sema init error\n");
		return 0;
	}

	ret = pthread_create(&pthread, NULL, thread_function1,NULL);
	if(ret !=0 ){
		printf("create thread1 error\n");
		return 0;
	}

	sleep(5);

	ret = pthread_create(&pthread, NULL, thread_function2, NULL);
	if(ret !=0 ){
		printf("create thread2 error\n");
		return 0;
	}

	while(1){};
}

抱歉!评论已关闭.