跟我一起做面试题-linux线程编程(5)

如题所述:

生产者消费者问题

这是一个非常经典的多线程题目,题目大意如下:有一个生产者在生产产品,这些产品将提供给若 干个消费者去消费,为了使生产者和消费者能并发执行,在两者之间设置一个有多个缓冲区的缓冲池,生产者将它生产的产品放入一个缓冲区中,消费者可以从缓冲 区中取走产品进行消费,所有生产者和消费者都是异步方式运行的,但它们必须保持同步,即不允许消费者到一个空的缓冲区中取产品,也不允许生产者向一个已经 装满产品且尚未被取走的缓冲区中投放产品。

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <string.h>
  4 #include <pthread.h>
  5 #include <errno.h>
  6 #include <stdarg.h>
  7 #include <unistd.h>
  8 #include <limits.h>
  9 #include <sys/ipc.h>
 10 #include <sys/msg.h>
 11 #include <sys/types.h>
 12 #include <sys/time.h>
 13 #include <signal.h>
 14
 15
 16 #define FULL    5           // 仓库满状态,抢iphone哟,这么少
 17 #define EMPTY   0           //  仓库空状态
 18 #define INIT_DEPOT_NUM  2   // 初始仓库状态
 19 #define CONSUMER_NUM 9     //  消费者数量
 20 #define PRODUCER_NUM 1      // 生产者数量
 21 #define RUN     0           //  系统运行状态
 22 #define OVER    1           // 系统关闭状态
 23
 24 int product;                //  具体仓库里的产品
 25 int shutdown;
 26 pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
 27 pthread_cond_t  product_cond = PTHREAD_COND_INITIALIZER;
 28 pthread_cond_t  consume_cond = PTHREAD_COND_INITIALIZER;
 29
 30
 31 #define myprintf( ... )  32     do{  33     mprintf(__FILE__, __FUNCTION__, __LINE__,##__VA_ARGS__);  34     }while(0)
 35
 36
 37
 38
 39 int mprintf(const char *file_name, const char *func_name, int line, const char *fmt, ...)
 40 {
 41     va_list     strArgPtr;
 42     int la,lb;
 43     la = fprintf(stdout, "[%-15s]-[%-10s]-[%04d]", file_name, func_name, line);
 44     va_start(strArgPtr, fmt);
 45     lb = vfprintf(stdout, fmt, strArgPtr);
 46     va_end(strArgPtr);
 47     printf("\n");
 48     fflush(stdout);
 49     return (la+lb);
 50 }
 51
 52 void * fun_producer(void *arg)
 53 {
 54     int i;
 55     int name = (int)arg;
 56     for(;;)
 57     {
 58             if( pthread_mutex_lock(&mylock))
 59             {
 60                 myprintf("pthread_mutex_lock error errmsg[%s]\n", strerror(errno));
 61                 exit(0);
 62             }
 63             while(1)
 64             {
 65                 if(shutdown == OVER)
 66                 {
 67                     myprintf("producer id [%d] go home now", name);
 68                     if(pthread_mutex_unlock(&mylock))
 69                     {
 70                         myprintf("pthread_mutex_unlock error errmsg[%s]\n", strerror(errno));
 71                         exit(0);
 72                     }
 73                     pthread_exit(NULL);
 74                 }
 75                 if ( product >= FULL)
 76                 {
 77                      myprintf("producer id [%d] prompt depot full [%d]",name, product);
 78                      break;
 79                 }
 80                 else
 81                 {
 82                     product++;
 83                     myprintf("producer id [%d] put product [%d] into depot",name, product);
 84                     break;
 85                 }
 86
 87                 if(pthread_cond_wait(&product_cond, &mylock))
 88                 {
 89                     myprintf("wait error errmsg[%s]\n", strerror(errno));
 90                     exit(0);
 91                 }
 92             }
 93             if(pthread_mutex_unlock(&mylock))
 94             {
 95                 myprintf("pthread_mutex_unlock error errmsg[%s]\n", strerror(errno));
 96                 exit(0);
 97             }
 98             if(pthread_cond_broadcast(&consume_cond))
 99             {
100                 myprintf("pthread_cond_broadcast error errmsg[%s]\n", strerror(errno));
101                 exit(0);
102             }
103             //sleep(1);
104     }
105 }
106
107 void * fun_consumer(void *arg)
108 {
109     int i;
110     int name = (int)arg;
111     for(;;)
112     {
113             if( pthread_mutex_lock(&mylock))
114             {
115                 myprintf("pthread_mutex_lock error errmsg[%s]\n", strerror(errno));
116                 exit(0);
117             }
118             while(1)
119             {
120                 if(shutdown == OVER)
121                 {
122                     myprintf("consumer id [%d] go home now", name);
123                     if(pthread_mutex_unlock(&mylock))
124                     {
125                         myprintf("pthread_mutex_unlock error errmsg[%s]\n", strerror(errno));
126                         exit(0);
127                     }
128                     pthread_exit(NULL);
129                 }
130                 if ( product > EMPTY)
131                 {
132                      myprintf("consumer id [%d] take product from depot [%d]", name, product);
133                      product--;
134                      break;
135                 }
136                 if(pthread_cond_wait(&consume_cond, &mylock))
137                 {
138                     myprintf("wait error errmsg[%s]\n", strerror(errno));
139                     exit(0);
140                 }
141             }
142             if(pthread_mutex_unlock(&mylock))
143             {
144                 myprintf("pthread_mutex_unlock error errmsg[%s]\n", strerror(errno));
145                 exit(0);
146             }
147             if(pthread_cond_broadcast(&product_cond))
148             {
149                 myprintf("pthread_cond_broadcast error errmsg[%s]\n", strerror(errno));
150                 exit(0);
151             }
152             //sleep(1);
153     }
154 }
155
156 void allover(int sig)
157 {
158         if( pthread_mutex_lock(&mylock))
159         {
160             myprintf("pthread_mutex_lock error errmsg[%s]\n", strerror(errno));
161             exit(0);
162         }
163         shutdown = OVER;
164         if( pthread_mutex_unlock(&mylock))
165         {
166             myprintf("pthread_mutex_lock error errmsg[%s]\n", strerror(errno));
167             exit(0);
168         }
169         if(pthread_cond_broadcast(&consume_cond))
170         {
171             myprintf("pthread_cond_broadcast error errmsg[%s]\n", strerror(errno));
172             exit(0);
173         }
174         if(pthread_cond_broadcast(&product_cond))
175         {
176             myprintf("pthread_cond_broadcast error errmsg[%s]\n", strerror(errno));
177             exit(0);
178         }
179 }
180
181
182 int appInit()
183 {
184     shutdown = RUN;
185     int i;
186     product = INIT_DEPOT_NUM;
187     if ( signal(SIGUSR1, allover)== SIG_ERR)
188     {
189         myprintf("signal  failure");
190         return -1;
191     }
192     if ( signal(SIGTERM, allover)== SIG_ERR)
193     {
194         myprintf("signal  failure");
195         return -1;
196     }
197     if ( signal(SIGINT, allover)== SIG_ERR)
198     {
199         myprintf("signal  failure");
200         return -1;
201     }
202     if ( signal(SIGQUIT, allover)== SIG_ERR)
203     {
204         myprintf("signal  failure");
205         return -1;
206     }
207 //    pthread_mutex_init(&mylock, NULL);
208 //    pthread_cond_init(&cond, NULL);
209     return 0;
210 }
211
212 int appDone()
213 {
214     int i;
215 //    pthread_cond_destroy(&cond);
216 //    pthread_mutex_destroy(&mylock);
217     return 0;
218 }
219
220 int main(int argc, char *argv[])
221 {
222
223     pthread_t consumer[CONSUMER_NUM];
224     pthread_t producer[PRODUCER_NUM];
225
226     int ret;
227     int i;
228     ret = appInit();
229     if(ret)
230     {
231         myprintf("appinit failure");
232         return -1;
233     }
234
235     for( i = 0; i < CONSUMER_NUM; i++)
236     {
237         ret = pthread_create(&consumer[i], NULL, fun_consumer, (void*)i);
238         if(ret)
239         {
240             myprintf("pthread_create ta error [%s]", strerror(errno));
241             return 1;
242         }
243     }
244
245     for( i = 0; i < PRODUCER_NUM; i++)
246     {
247         ret = pthread_create(&producer[i], NULL, fun_producer, (void*)i);
248         if(ret)
249         {
250             myprintf("pthread_create ta error [%s]", strerror(errno));
251             return 1;
252         }
253     }
254     for( i = 0; i < CONSUMER_NUM; i++)
255         pthread_join(consumer[i], NULL);
256     for( i = 0; i < PRODUCER_NUM; i++)
257         pthread_join(producer[i], NULL);
258
259     myprintf("main thread exit");
260     ret = appDone();
261     if(ret)
262     {
263         myprintf("appDone failure");
264         return -1;
265     }
266     return 0;
267 }

代码一般在以前的基础上更改,有些bug的修复并不会同步到之前的版本。以最新版本为要。

本版本增加一个控制,对一些常用信号给出响应,并结束程序。




跟我一起做面试题-linux线程编程(5)

时间: 2024-07-29 16:38:53

跟我一起做面试题-linux线程编程(5)的相关文章

跟我一起做面试题-linux线程编程(7)

一直以来难以调试多线程,在网上搜索得知一种多线程调试的方法 一直觉得Linux下的多线程调试是很麻烦的,因为一般大一点的程序线程会很多,通过gdb的info thread命令看全都是系统调用,看不到详细的方法,至少我看到是这样的...如果用thread id跟进每个thread去bt,是件相当痛苦的事情,特别是你info thread看到近百个线程的时候T_T.而且大多时候等待重现问题或重启程序的时间代价是相当高的,在程序运行的情况下查看thread堆栈情况就显得 很重要了. 其实有pstack

跟我一起做面试题-linux线程编程

如题所述: 编写程序完成如下功能: 1)有一int型全局变量g_Flag初始值为0: 2) 在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1 3) 在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2 4) 线程序1需要在线程2退出后才能退出 5) 主线程在检测到g_Flag从1变为2,或者从2变为1的时候退出 #include <stdio.h> #include <stdlib.h> #include &l

跟我一起做面试题-linux线程编程(4)

如题所述: 有四个线程1.2.3.4.线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD.初始都为空.现要让四个文件呈如下格式: A:1 2 3 4 1 2.... B:2 3 4 1 2 3.... C:3 4 1 2 3 4.... D:4 1 2 3 4 1.... 请设计程序. 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #in

跟我一起做面试题-linux线程编程(3)

如题所述: 编写一个程序,开启3个线程,这3个线程的ID分别为A.B.C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示:如:ABCABC….依次递推. ----------------------------------------------------------------------------------------------------------------- 用pthread_cond_signal,理论上会引起本该得到信号的线程一直处于饥饿状态,

Linux线程编程之信号处理

前言 Linux多线程环境中的信号处理不同于进程的信号处理.一方面线程间信号处理函数的共享性使得信号处理更为复杂,另一方面普通异步信号又可转换为同步方式来简化处理. 本文首先介绍信号处理在进程中和线程间的不同,然后描述相应的线程库函数,在此基础上给出一组示例代码,以讨论线程编程中信号处理的细节和注意事项.文中涉及的代码运行环境如下: 本文通过sigwait()调用来“等待”信号,而通过signal()/sigaction()注册的信号处理函数来“捕获”信号,以体现其同步和异步的区别. 一  概念

Linux线程编程之生产者消费者问题

前言 本文基于顺序循环队列,给出Linux生产者/消费者问题的多线程示例,并讨论编程时需要注意的事项.文中涉及的代码运行环境如下: 本文假定读者已具备线程同步的基础知识. 一  顺序表循环队列 1.1 顺序循环队列定义 队列是一种运算受限的先进先出线性表,仅允许在队尾插入(入队),在队首删除(出队).新元素入队后成为新的队尾元素,元素出队后其后继元素就成为队首元素. 队列的顺序存储结构使用一个数组和两个整型变量实现,其结构如下: 1 struct Queue{ 2 ElemType elem[M

linux 线程编程详解

1.线程的概念: 线程和进程有一定的相似性,通常称为轻量级的进程 同一进程中的多条线程将共享该进程中的全部系统资源,如虚拟地址空间,文件描述符和信号处理等等.但同一进程中的多个线程都有自身控制流 (它自己的指令计数器和cpu时钟)和各自的调用栈(call stack),自己的寄存器环境(register context),自己的线程本地存储(thread-local storage). 一个进程可以有很多线程,每条线程并行执行不同的任务. 线程可以提高应用程序在多核环境下处理诸如文件I/O或者s

Linux 线程编程2.0——线程同步-互斥锁

当我们需要控制对共享资源的存取的时候,可以用一种简单的加锁的方法来控制.我们可以创建一个读/写程序,它们共用一个共享缓冲区,使用互斥锁来控制对缓冲区的存取. 函数 pthread_mutex_init()用来生成一个互斥锁.其函数原型如下: #include<pthread.h> int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr): 第一个参数是互斥变量

嵌入式linux面试题解析(三)——Linux应用编程部分一

嵌入式linux面试题解析(三)--Linux应用编程部分一 1.TCP与UDP的区别 TCP:是面向连接的流传输控制协议,具有高可靠性,确保传输数据的正确性,有验证重发机制,不会出现丢失或乱序. UDP:是无连接的数据报服务,不对数据报进行检查与修改,无须等待对方的应答,会出现分组丢失.重复.乱序,但具有较好的实时性,UDP段结构比TCP的段结构简单,因此网络开销也小. 2.流量控制和拥塞控制 拥塞控制    网络拥塞现象是指到达通信子网中某一部分的分组数量过多,使得该部分网络来不及处理,以致