snifer

[原创]UCLinux系统下的多线程的设计

0
阅读(3379)

在使用blanfin系列处理器时候,经常需要涉及到多线程的编程,使一些初学者的梦魇,今天正好写一下这方面的内容,与大家一起共勉!!!

ucLinux系统下的多线程遵循POSIX线程接口 ,称为 pthread 头文件 pthread.h 连接时需要使用库 libpthread.a
npthread_create创建线程
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg);
npthread_t是线程结构,用来保存线程相关数据,你也可以理解为是线程类型,声明一个线程对象(变量)。
npthread_join等待线程结束
/* example.c*/
#include
#include
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!\n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.\n");
pthread_join(id,NULL);
return (0);
}
gcc example1.c -lpthread -o example1
运行example1,我们得到如下结果:
This is the main process.
This is a pthread.
This is the main process.
This is the main process.
This is a pthread.
This is a pthread.
再次运行,我们可能得到如下结果:
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.

良好的程序设计风格必须遵循:
1全局变量用具有描述意义的名字,局部变量用短名字。函数采用动作性的名字。保持一致性。
2缩进形式显示程序结构,使用一致的缩行和加括号风格。使用空行显示模块
3充分而合理地使用程序注释给函数和全局数据加注释。不要注释不好的代码,应该重写。不要与代码矛盾。
4友好的程序界面,程序界面的方便性及有效性
5不要滥用语言技巧使用表达式的自然形式。利用括号排除歧义。分解复杂的表达式。当心副作用,像++这一类运算符具有副作用。
6程序的健壮性:容错
7模块化编程
Baidu
map