您的位置:首页 > 运维架构 > Linux

Linux下多线程编程简介(六)

2009-11-25 17:40 417 查看
本篇将根据前面所学的知识,设计一个简单的生产者/消费者模式。

有一个缓冲区和两个线程:生产者和消费者。生产者把产品放入缓冲区,而消费者从缓冲区中拿走。当缓冲区满时,生产者必须等待;另外,当缓冲区空时,消费者必须等待,并且缓冲区不能同时进行生产者和消费者的操作。

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <semaphore.h>

#define return_if_fail(p) \
if(!p) { printf("[%s]:func error!", __func__); return; }

typedef struct _PrivInfo {
sem_t empty;
sem_t full;
char buf[50];
time_t end_time;
}PrivInfo;

void info_init(PrivInfo *thiz);
void info_destroy(PrivInfo *thiz);
void *productor(void *paramthiz);
void *consumer(void *paramthiz);

int main (int argc, char** argv) {
pthread_t pt_1 = 0;
pthread_t pt_2 = 0;
int ret = 0;
PrivInfo *thiz = NULL;
thiz = (PrivInfo*)malloc(sizeof(PrivInfo));
if(NULL == thiz) {
return -1;
}
info_init(thiz);
ret = pthread_create(&pt_1, NULL, productor, (void*)thiz);
if(0 != ret) {
perror("pthread1 creation failed!");
}

ret = pthread_create(&pt_2, NULL, consumer,(void*)thiz);
if(0 != ret) {
perror("pthread2 creation failed!");
}
pthread_join(pt_1, NULL);
pthread_join(pt_2, NULL);
info_destroy(thiz);

free(thiz);
thiz = NULL;

return 0;
}

void info_init(PrivInfo *thiz) {
return_if_fail(&thiz != NULL);
thiz->end_time = time(NULL) + 10;
sem_init(&thiz->empty, 0, 1);
sem_init(&thiz->full, 0, 0);

memset(thiz->buf, 0, sizeof(thiz->buf));

return;
}

void info_destroy(PrivInfo *thiz) {
return_if_fail(&thiz != NULL);
sem_destroy(&thiz->empty);
sem_destroy(&thiz->full);

return;
}

void *productor(void *paramthiz) {
int i = 0;
PrivInfo *thiz = (PrivInfo *)paramthiz;
while(time(NULL) < thiz->end_time) {
sem_wait(&thiz->empty);

for(; i<4; i++) {
thiz->buf[i] = 0x41 + i;
}

sem_post(&thiz->full);
sleep(1);
}
pthread_exit(NULL);
}

void *consumer(void *paramthiz) {
int numread = 0;
PrivInfo *thiz = (PrivInfo *)paramthiz;
while(time(NULL) < thiz->end_time) {
sem_wait(&thiz->full);
printf("get the string from buffer is: %s\n", thiz->buf);
sem_post(&thiz->empty);
sleep(1);
}

pthread_exit(NULL);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: