注意:消息是由主线程产生的,而消息这时候在堆中,两个线程通过全局变量获取访问消息。
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
struct msg {
int data;
struct msg *m_next;
/* ... more stuff here ... */
};
struct msg *workq;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
void
process_msg(void)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&qlock);
while (workq == NULL)
pthread_cond_wait(&qready, &qlock);
mp = workq;
workq = mp->m_next;
pthread_mutex_unlock(&qlock);
/* now process the message mp */
printf("deal the mp. the data is %d\n",mp->data);
free(mp);
}
}
void
enqueue_msg(struct msg *mp)
{
pthread_mutex_lock(&qlock);
mp->m_next = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
void* thr_fn(void* arg){
process_msg();
return ((void*)1);
}
int main(){
pthread_t tid1;
pthread_t tid2;
int err;
err = pthread_create(&tid1,NULL,thr_fn,NULL);
if(err !=0){
err_quit("can't create thread%s\n",strerror(err));
}
err = pthread_create(&tid2,NULL,thr_fn,NULL);
if(err !=0){
err_quit("cant' create thread%s\n",strerror(err));
}
printf("create success.\n");
struct msg* mp = malloc(sizeof(struct msg));
mp->m_next = NULL;
mp->data = 110;
enqueue_msg(mp);
//sleep(5);
sleep(1);
pthread_cancel(tid1);
pthread_cancel(tid2);
//pthread_cancel(tid1);
//pthread_cancel(tid2);
printf("ok\n");
}
本文介绍了一个基于 POSIX 线程的简单消息传递机制实现。该机制利用条件变量和互斥锁确保线程间安全地共享消息队列。文章详细展示了如何创建消息结构、如何向队列中添加消息以及如何从队列中处理并移除消息。
1032

被折叠的 条评论
为什么被折叠?



