对于多线程程序,可以用生产者与消费者模型来理解,其中需要线程、互斥锁、条件变量等等。其实很多项目中都可以看到它的影子,网络服务器程序网络IO事件可以看做产品,事件线程可以看成消费者,处理网络IO事件等等。
下面是在Linux下用c++实现的生产者与消费者模型
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <queue>
using namespace std;
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
int gIndex = 0;
queue<int> gProducts;
//初始化互斥锁和条件变量
pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gCond = PTHREAD_COND_INITIALIZER;
void* producer(void* arg)
{
//在64位的机器上指针占用8个字节,int 占用四个字节,为了去除警告
cout << "producer index:" << (long)arg << endl;
for (int i = 0; i < 10; i++)
{
pthread_mutex_lock(&gMutex);
cout << "producer:" << (long)arg << "produce:" << gIndex++ << endl;
gProducts.push(gIndex);
pthread_cond_broadcast(&gCond);//向所有等待产品的消费者发消息
pthread_mutex_unlock(&gMutex);
sleep(1);
}
pthread_exit(NULL);
}
void* consumer(void* arg)
{
cout << "consumer index:" << (long)arg << endl;
while (1)
{
pthread_mutex_lock(&gMutex);
while (gProducts.size() <= 0)
{//收到消息,如果没有产品,继续等待
pthread_cond_wait(&gCond, &gMutex);
}
cout << "consumer:" << (long)arg << "consum:" << gProducts.front() << endl;
gProducts.pop();
pthread_mutex_unlock(&gMutex);
usleep(1000 * 200);
}
pthread_exit(NULL);
}
int main(void)
{
pthread_mutex_init(&gMutex, NULL);
pthread_cond_init(&gCond, NULL);
pthread_t tids[7];
int i, ret;
for (i = 0; i < 5; i++)
{
ret = pthread_create(&tids[i], NULL, producer, (void*)i);//只能传值,不能传地址
if (ret != 0)
{
ERR_EXIT("pthread_create producer thread fail");
}
}
for (; i < 7; i++)
{
ret = pthread_create(&tids[i], NULL, consumer, (void*)i);
if (ret != 0)
{
ERR_EXIT("pthread_create consumer thread fail");
}
}
for (i = 0; i < 7; i++)
{
pthread_join(tids[i], NULL);
}
return 0;
}
编译一下,然后执行