好久没有更新BLOG了,最近在做语音识别和语音合成方面的工作,粘一段自已写的用得比较多的LINUX多线程代码,做个记录,方面以后查阅吧。代码的作用是,主线程负责将要处理的数据放入队列,另外一个新线程负责处理队列中的数据,如果没有数据新线程将睡眠等待,有新数据到来时主线程会唤醒新线程,就这么简单。。。随手写的程序,存在问题希望能告诉我:)
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <pthread.h> #ifndef BOOL #define BOOL int #endif #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static BOOL bIncomingNewData=FALSE; pthread_cond_t condDataready = PTHREAD_COND_INITIALIZER; /* 条件变量 */ pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; /* 互斥量 */ #define QUEUE_SIZE 255 static void* queueArray[QUEUE_SIZE]; /* 用数组实现环型队列 */ static int queueFront = -1; /* 队首 */ static int queueEnd = -1; /* 队尾 */ /* 入队 */ static int inQueue(void* p) { if (queueFront == -1 && queueEnd == -1) { queueFront = queueEnd = 0; queueArray[queueFront] = p; return 0; } int end = queueEnd + 1; if (end >= QUEUE_SIZE) { end = 0; } /* 队列已经满了*/ if (end == queueFront) { return -1; } queueArray[end] = p; queueEnd = end; return 0; } /* 出队 */ static void* outQueue() { /* 队列是空的 */ if (queueFront == -1 && queueEnd == -1) { return 0; } void* pRet; if (queueFront == queueEnd) { pRet = queueArray[queueFront]; queueFront = queueEnd = -1; return pRet; } pRet = queueArray[queueFront++]; if (queueFront >= QUEUE_SIZE) { queueFront = 0; } return pRet; } /* 线程函数 */ void* threadFunc(void* arg) { static void* localArray[QUEUE_SIZE]; static int localDataCount = 0; void* pData; int i; for (;;) { pthread_mutex_lock(&lock); /* 睡眠并等待队列中有数据 */ while (!bIncomingNewData) { pthread_cond_wait( &condDataready, &lock ); } /* 将数据复到到局部数量等待处理 */ while ((pData = outQueue()) != 0) { localArray[localDataCount++] = pData; if (localDataCount >= QUEUE_SIZE) { break; } } bIncomingNewData = FALSE; pthread_mutex_unlock(&lock); /* 逐个处理数据 */ for (i=0; i<localDataCount; i++) { printf( "/n ## processing %d ## /n", (int)localArray[i] ); sleep(5); } localDataCount = 0; } } int main(void) { pthread_t threadId; int data; int err = pthread_create(&threadId, NULL, threadFunc, NULL); if (err != 0) { printf( "can't create thread!/n" ); return -1; } while (1) { printf( ">>> input a number to process: " ); scanf( "%d", &data); getchar(); pthread_mutex_lock(&lock); /* 添加数据入队列,并唤醒线程 */ if (inQueue((void*)data) == 0) { bIncomingNewData = TRUE; pthread_cond_signal( &condDataready ); } pthread_mutex_unlock(&lock); } err = pthread_join( threadId, NULL ); if (err != 0) { printf( "pthread_join return error!/n" ); return -1; } return 0; } |