UNIX环境高级编程学习之第十一章线程-使用条件变量

Linux/Unix C/C++ xiujie 191℃ 0评论 已收录

UNIX环境高级编程学习之第十一章线程-使用条件变量

/* 
FileName: condMutexLock.c 
Date: 20100617
Desc: g++ condMutexLock.c -lpthread -o demo 
	使用条件变量
*/  
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;  // 互斥锁定义并初始化
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;     // 条件变量定义并初始化
struct msg {   // 链表
	struct msg *m_next;
    char  data[100];        //  处理数据
};
struct msg * msgHead = NULL;
void* thread_fun(void * arg)
{
	struct msg *msgCur;  // 当前数据
	while (1)
	{
		pthread_mutex_lock(&g_mutex);
		while(msgHead == NULL)
			pthread_cond_wait(&g_cond, &g_mutex);
		msgCur = msgHead;
		msgHead = msgHead->m_next;
		/* 处理数据  msgCur */
		printf("Data:%s/n", msgCur->data);
		free(msgCur);
		msgCur = NULL;
		pthread_mutex_unlock(&g_mutex);
	}
	return (void*)1;
}

int main(int argc, char* argv[])
{
	int ret;
	pthread_t t;
	ret = pthread_create(&t, NULL, thread_fun, NULL);
	if (ret != 0)
	{
			printf("pthread_create() is Error t1 /n");
			exit(-1);
	}
	/* 每隔两秒添加一次数据 */
	struct msg *msgCur;
	while (1)
	{
		pthread_mutex_lock(&g_mutex);
		msgCur = malloc(sizeof(struct msg));
		if (msgCur == NULL)
		{
			printf("malloc() is Failed! /n");
			exit(-1);
		}
		memset(msgCur, 0x00, sizeof(struct msg));
		msgCur->m_next = msgHead;
		strcpy(msgCur->data, "Hello");
		msgHead = msgCur;
		pthread_mutex_unlock(&g_mutex);
		pthread_cond_signal(&g_cond);
		sleep(2);
	}
	pthread_mutex_destroy(&g_mutex); // 销毁互斥锁
	pthread_cond_destroy(&g_cond); // 销毁条件
	return 0;
}


喜欢 (0)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址