我正在开发一个用C实现的固件应用程序,我想知道这种问题的优秀设计模式是什么:
我已经考虑了STATE机器,但我仍然认为实现不优雅,因为我在等待主循环中的响应,转移到另一个状态。
我应该实施哪种设计模式?
答案 0 :(得分:2)
这听起来像是一个简单的客户端 - 服务器(消费者 - 生产者)模型问题。
简答:监控设计模式。
答案很长......
当您说“我将获得中断”时,您是说会触发硬件中断,还是会发生执行更改?在硬件中断的情况下,这将是特定于平台的。 Even something as simple as a keyboard hardware interrupt routine takes a bit of effort to implement
如果是另一种情况,你可以拥有一个主/经理线程,一个工作线程,以及:
不是旋转锁定,而是使用condvar(condition variable),这样就不会烧掉CPU并且不必要地浪费周期。
/*
* Solution to Producer Consumer Problem
* Using Ptheads, a mutex and condition variables
* From Tanenbaum, Modern Operating Systems, 3rd Ed.
*/
/*
In this version the buffer is a single number.
The producer is putting numbers into the shared buffer
(in this case sequentially)
And the consumer is taking them out.
If the buffer contains zero, that indicates that the buffer is empty.
Any other value is valid.
*/
#include <stdio.h>
#include <pthread.h>
#define MAX 10000000000 /* Numbers to produce */
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void* producer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex); /* protect buffer */
while (buffer != 0) /* If there is something
in the buffer then wait */
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
pthread_cond_signal(&condc); /* wake up consumer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
void* consumer(void *ptr) {
int i;
for (i = 1; i <= MAX; i++) {
pthread_mutex_lock(&the_mutex); /* protect buffer */
while (buffer == 0) /* If there is nothing in
the buffer then wait */
pthread_cond_wait(&condc, &the_mutex);
buffer = 0;
pthread_cond_signal(&condp); /* wake up consumer */
pthread_mutex_unlock(&the_mutex); /* release the buffer */
}
pthread_exit(0);
}
int main(int argc, char **argv) {
pthread_t pro, con;
// Initialize the mutex and condition variables
/* What's the NULL for ??? */
pthread_mutex_init(&the_mutex, NULL);
pthread_cond_init(&condc, NULL); /* Initialize consumer condition variable */
pthread_cond_init(&condp, NULL); /* Initialize producer condition variable */
// Create the threads
pthread_create(&con, NULL, consumer, NULL);
pthread_create(&pro, NULL, producer, NULL);
// Wait for the threads to finish
// Otherwise main might run to the end
// and kill the entire process when it exits.
pthread_join(&con, NULL);
pthread_join(&pro, NULL);
// Cleanup -- would happen automatically at end of program
pthread_mutex_destroy(&the_mutex); /* Free up the_mutex */
pthread_cond_destroy(&condc); /* Free up consumer condition variable */
pthread_cond_destroy(&condp); /* Free up producer condition variable */
}
答案 1 :(得分:0)
我会使用&#34; divide&amp;征服&#34;将您的问题分解为可管理的子问题的原则。您可以在不同的抽象级别中使用以下模式:
您可以找到许多摘要和对上述示例的参考 和eswp3.org上的C中的其他设计模式。 (对不起,我无法做到 目前超过2个网站的超链接。我会在赚钱后这样做 足够的声誉...)