首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

基于xilkernel的嵌入式应用程序设计方法 03

基于xilkernel的嵌入式应用程序设计方法 03

thread表明线程id,attr指出线程属性,start_func函数指针是线程创建成功后开始执行的函数,param是这个函数的一个唯一的参数。
在静态任务中调用这些函数来产生一些有优先级的任务。如下例:
static pthread_t tid0,tid1;
static pthread_attr_t attr;
static struct sched_param prio;
void * first_thread () { ......
pthread_attr_init(&attr);
prio.sched_priority = 4;
pthread_attr_setschedparam (&attr,&prio);
ret = pthread_create (&tid0, &attr, (void*)important_task, null);
pthread_attr_init (&attr);
prio.sched_priority = 5;
pthread_attr_setschedparam (&attr,&prio);
ret = pthread_create (&tid1, &attr, (void*)second_important_task, null);
......
}
这样,系统会发起important_task和second_important_task两个任务,important_task的优先级比second_important_task高,会优先运行。除非important_task任务阻塞或退出,second_important_task才可能得到运行。
posix无名信号量

信号量提供高速的任务间同步和互斥机制。对于互斥,信号量可以上锁共享资源,使得该共享资源在同一时刻只有一个线程所拥有。关于此信号量的一些常用函数如下:
int sem_init(sem_t *sem,int pshared,unsigned int value);
int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);
sem_init()创建一个信号量,并初始化信号量的值为value;sem_wait()调用将阻塞进程,直到信号量的值大于0,此函数返回时信号量的值减1;sem_post()是将信号量的值加1,并发出信号唤醒等待的进程。

信号量用于同步,一般要初始化为0,等待要同步的任务阻塞在sem_wait()调用上。任务调用sem_post来解锁该信号量,来达到同步。下面一个例子是用信号量实现同步操作的:
static sem_t protect;
void * first_thread (){ ......
sem_init(&protect, 1, 0);
......
}
void* thread_func1 (){ ......
while(1){
sem_wait(&protect);
......
}
}
void* thread_func2 (){ ......
while(1){......
if(某种条件成立)sem_post(&protect);
}
}
当信号量用于互斥时,一般要初始化为一个大于0的值,就可以让资源可用。如果信号量的初始值为1,第一个上锁该信号量的线程会立即执行,后继的线程将会阻塞,直到下次信号量解锁才会执行。
xsi消息队列

消息队列允许长度可变、数目可变的消息排队。任何任务或中断服务程序可以发送消息到消息队列。任何任务可从消息队列接收消息。关于此消息队列的一些常用函数如下:
int msgget(key_t key, int msgflg)
int msgsnd (int msqid, const void *msgp, size_t msgsz, int msgflg)
ssize_t msgrcv (int msqid, void *msgp, size_t nbytes, long msgtyp, int msgflg)
msgget()来创建一个消息队列,key是消息队列的标识符,msgflag目前有两个选项,ipc_creat和ipc_excl。msgsnd()函数往队列发送一条消息,msgp是消息缓冲指向的指针,msgsz表示消息的字节数。msgrcv ()函数作用是从消息队列中读取消息,把接收到的消息拷贝到msgp指针指向的缓冲区,nbytes表示缓冲支持的消息字节数。发送和接收消息中的msqid是消息队列描述符,用来标识相关的消息队列。下面是消息队列单向通信的简单代码:
struct _msg {
short type;
char first;
char last;
};
static struct _msg msg_p;
static struct _msg msg_c;
static int msgid;
void * first_thread (){ ......
msgid = msgget(5,ipc_creat | ipc_excl);
......
}
void* consumer ()
{
while(1) {
msgrcv( msgid, &msg_c, 4, 0,0 );
......
}
}
void* producer ()
{
while(1) {......
msgsnd (msgid, &msg_p, 4, 0);
}
}
在例子开始,建立消息的数据结构。在producer()中操作消息的各项数据,通过msgsnd()发送此消息。在consumer()中,如果消息队列里没有消息,则msgsnd()阻塞此线程,直到消息队列非空时,
返回列表