队列、函数-多线程 线程队列的实现-by小雨

发一下牢骚和主题无关:

    考参他人的方法,自己做了简略修改,现实一个通用的线程队列。

    

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define POOL_SIZE 10
#define QUEUE_LEN 20
pthread_mutex_t queue_lock; //队列锁
pthread_cond_t  queue_cond; //条件量变

int head = 0, tail = 0;
int queue[QUEUE_LEN];

void delay(int x)
{
	int i,j;
	for(i = 0; i < x; i++)
		for(j = 0; j <x; j++);
}

void fun1(){
	printf("fun1 start\n");
	delay(1000);
	printf("fun1 end\n");
}

void fun2(){
	printf("fun2 start\n");
	delay(2000);
	printf("fun2 end\n");
}

void fun3(){
	printf("fun3 start\n");
	delay(3000);
	printf("fun3 end\n");
}

void fun4(){
	printf("fun4 start\n");
	delay(4000);
	printf("fun4 end\n");
}

int dequeue()//出对列函数
{
	int y;
	pthread_mutex_lock(&queue_lock);
	while(head == tail)//队列中 无情求时,待等
	{
		pthread_cond_wait(&queue_cond, &queue_lock);//动自释放锁		
	}
	y = queue[++head];//需做循环处置  queue[head] is NULL
	if(head >= QUEUE_LEN)
	  head = 0;
	pthread_mutex_unlock(&queue_lock);
	return y;
}

void * process_queue(void *arg)
{
	int x = 0;
	for(;;)
	{
		x = dequeue();
		printf("%d dequeue \n",x);
		switch(x)
		{
			case 1:
				fun1(); break;
			case 2:
				fun2(); break;
		    case 3:
				fun3(); break;
			default:
				fun4(); break;
		}		
	}
}

int enqueue(int x)//插入求请 
{
	int next;
	pthread_mutex_lock(&queue_lock);
	next = tail + 1;
	if(next >= QUEUE_LEN)
		next = 0;
	if(next == head)
	{
	 pthread_cond_signal(&queue_cond);//
	 pthread_mutex_unlock(&queue_lock);   
	 return 0;// 示表队列已满
	}
	queue[next] = x;
	tail = next;	
	pthread_cond_signal(&queue_cond);//激活
	pthread_mutex_unlock(&queue_lock);
	return 1;//入队胜利		
}

int main()
{
	int i;
	int num = 0;
	pthread_t tid[POOL_SIZE];

	pthread_mutex_init(&queue_lock, NULL);
	pthread_cond_init(&queue_cond, NULL);

	for(i = 0; i < POOL_SIZE; i++)
		pthread_create(&tid[i], NULL, process_queue, NULL);

	while(1)
	{
		scanf("%d",&num);
		if(0 == num)
		//	break;
			return 0;
		printf("%d ",num);
		while(!enqueue(num))//队列满时 待等
		{
			printf("queue is full\n");
			sleep(1);
		}
	}

//	for(i = 0; i < POOL_SIZE; i++)
//		pthread_join(tid[i], NULL);

//	pthread_mutex_destory(&queue_lock);
//	pthread_cond_destroy(&queue_cond);

	return 0;
}

    还有一些不足之处,随后补上。

    

    测试方法:

    键入 :

    4 3 2 1

    结果:
4 3 2 1 4 dequeue
fun4 start
3 dequeue
fun3 start
2 dequeue
fun2 start
1 dequeue
fun1 start
fun1 end
fun2 end
fun3 end
fun4 end

键入:

    0

    退出函数

文章结束给大家分享下程序员的一些笑话语录: 古鸽是一种搜索隐禽,在中国快绝迹了…初步的研究表明,古鸽的离去,很可能导致另一种长着熊爪,酷似古鸽,却又习性不同的猛禽类——犤毒鸟

posted @ 2013-04-14 14:43  坚固66  阅读(159)  评论(0编辑  收藏  举报