`
vearne
  • 浏览: 18298 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

linux线程同步--条件变量练习(2)

阅读更多

 注意:消息是由主线程产生的,而消息这时候在堆中,两个线程通过全局变量获取访问消息。

#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");
}

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics