#include <stdio.h>
#include <pthread.h>
struct msg {
int data;
struct msg* next_msg;
};
struct msg * workq;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
void init_queue(void){
pthread_mutex_lock(&qlock);
workq=NULL;
pthread_mutex_unlock(&qlock);
}
void enqueue_msg(struct msg* mp){
pthread_mutex_lock(&qlock);
mp->next_msg = workq;
workq = mp;
pthread_mutex_unlock(&qlock);
pthread_cond_signal(&qready);
}
struct msg *queue_msg(void){
struct msg *mp;
pthread_mutex_lock(&qlock);
while(workq == NULL)
pthread_cond_wait(&qready,&qlock);
mp = workq;
workq = mp->next_msg;
pthread_mutex_unlock(&qlock);
return mp;
}
void process_msg(int pid){
struct msg *mp;
printf("thread %d created.\n",pid);
for(;;)
{
mp=queue_msg();
printf("thread %d deal the msg.data is %d \n",pid,mp->data);
struct msg msgx;
msgx.data = mp->data+1;
msgx.next_msg = NULL;
enqueue_msg(&msgx);
sleep(3);
}
}
void * thr_fn(void*arg)
{
process_msg(*(int*)arg);
return ((void*)1);
}
void main(){
pthread_t tid1, tid2;
int err;
int pid1 = 1, pid2 = 2;
if(err = pthread_create(&tid1,NULL,thr_fn,&pid1))
{
printf("can't create thread %d \n",err);
}
if(err = pthread_create(&tid2,NULL,thr_fn,&pid2))
{
printf("can't create thread %d \n",err);
}
printf("create thread success.\n");
sleep(1);
struct msg msg1;
msg1.data=100;
msg1.next_msg = NULL;
init_queue();
enqueue_msg(&msg1);
printf("add a msg .\n");
sleep(3);
printf("OK\n");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
c++ 异步消息队列
最新推荐文章于 2024-11-09 16:02:37 发布