Linux线程同步(消息队列)

分两个c源文件queue.c main.c,代码如下:

queue.c

#include


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;
}

main.c

#include
#include
#include
#include

struct msg {
int data;
struct msg* next_msg;
};

extern void enqueue_msg(struct msg* mp);
extern void init_queue(void);
extern struct msg * queue_msg(void);

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;
pthread_t  tid2;
int err;
int pid=1;
err=pthread_create(&tid1,NULL,thr_fn,&pid);
if(err!=0){
    printf("can't create thread %d \n",err);
}
int pid1=2;
err=pthread_create(&tid2,NULL,thr_fn,&pid1);
if(err!=0){
    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);

}

 

在ubuntu14.04下编译 :

gcc  queue.c main.c -o  milk  -lpthread

chmod a+x milk

./milk

你可能感兴趣的:(Linux线程同步(消息队列))