读TI的demo代码有感——main和线程函数的设计
时间:2009-08-21 来源:逼良为娼
工作没多久,就写些读别人代码的体会吧。
公司开发用TI的产品,所以偶也有幸读到了一些他们的代码。。。他们的代码架构设计得就是好,一层一层,很清晰,下面就说下他们的main函数和线程函数的设计吧。以程序为例。
在头文件中:
... /* 包含其他一些头文件 */
/* Thread error codes */
#define THREAD_SUCCESS (Void *) 0
#define THREAD_FAILURE (Void *) -1 static inline Void gblSetQuit(void)
{
pthread_mutex_lock(&gbl.mutex); /* 其中gbl是个全局结构体类型变量 */
gbl.quit = TRUE; /* 设置退出状态为真 */
pthread_mutex_unlock(&gbl.mutex);
} /* Functions to protect the global data */
static inline Int gblGetQuit(void)
{
Int quit; pthread_mutex_lock(&gbl.mutex);
quit = gbl.quit;
pthread_mutex_unlock(&gbl.mutex); return quit;
} #define cleanup(x) status = (x); \ gblSetQuit(); \ goto cleanup ... 在源文件中: ... /* 包含相关头文件 */ int main() { /* 定义相关变量 */ pthread_t readThread; pthread_t writeThread; struct sched_param schedParam; ReadEnv readEnv; ... int status = EXIT_SUCCESS; if (pthread_attr_setschedparam(&attr, &schedParam)) {
ERR("Failed to set scheduler parameters\n");
cleanup(EXIT_FAILURE); } /* 初始化readEnv参数 */ ...
if (pthread_create(&readThread, &attr, readThrFxn, &readEnv)) {
ERR("Failed to create display thread\n");
cleanup(EXIT_FAILURE);
} ... cleanup: /* 做退出前的相应处理,如关闭打开的文件等 */ ... return status;
} void *readThrFxn(void *arg) { /* 定义变量 */ int status = THREAD_SUCCESS; ... if (...) { /* 失败处理 */ .... return THREAD_FAILURE; } while (!gblGetQuit()) { /* 其他线程或主函数没退出时循环做某事 */ ... } cleanup: /* 线程退出前处理,如关闭打开的文件...*/ ... return status; }
#define THREAD_SUCCESS (Void *) 0
#define THREAD_FAILURE (Void *) -1 static inline Void gblSetQuit(void)
{
pthread_mutex_lock(&gbl.mutex); /* 其中gbl是个全局结构体类型变量 */
gbl.quit = TRUE; /* 设置退出状态为真 */
pthread_mutex_unlock(&gbl.mutex);
} /* Functions to protect the global data */
static inline Int gblGetQuit(void)
{
Int quit; pthread_mutex_lock(&gbl.mutex);
quit = gbl.quit;
pthread_mutex_unlock(&gbl.mutex); return quit;
} #define cleanup(x) status = (x); \ gblSetQuit(); \ goto cleanup ... 在源文件中: ... /* 包含相关头文件 */ int main() { /* 定义相关变量 */ pthread_t readThread; pthread_t writeThread; struct sched_param schedParam; ReadEnv readEnv; ... int status = EXIT_SUCCESS; if (pthread_attr_setschedparam(&attr, &schedParam)) {
ERR("Failed to set scheduler parameters\n");
cleanup(EXIT_FAILURE); } /* 初始化readEnv参数 */ ...
if (pthread_create(&readThread, &attr, readThrFxn, &readEnv)) {
ERR("Failed to create display thread\n");
cleanup(EXIT_FAILURE);
} ... cleanup: /* 做退出前的相应处理,如关闭打开的文件等 */ ... return status;
} void *readThrFxn(void *arg) { /* 定义变量 */ int status = THREAD_SUCCESS; ... if (...) { /* 失败处理 */ .... return THREAD_FAILURE; } while (!gblGetQuit()) { /* 其他线程或主函数没退出时循环做某事 */ ... } cleanup: /* 线程退出前处理,如关闭打开的文件...*/ ... return status; }
相关阅读 更多 +
排行榜 更多 +