1. 程式人生 > >多執行緒程式設計總結(二)——條件變數和互斥鎖

多執行緒程式設計總結(二)——條件變數和互斥鎖

#include <stdio.h>
#include <pthread.h>
#include <error.h>
#include <assert.h>
#include <stdlib.h>
typedef  int DataType;
typedef struct listNode
{
	struct listNode* _next;
	DataType _data;
}node, *pnode, *plist;

pnode listHead = NULL;
//定義成全域性,初始化簡單
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t  need_product = PTHREAD_COND_INITIALIZER;

pnode CreateNode(DataType data)
{
	pnode newnode = (pnode)malloc(sizeof(node));
	newnode->_data = data;
	newnode->_next = NULL;
	return newnode;
}

void Init(plist *list)
{
	if (NULL != list)
	{
		*list = NULL;
	}
}

void PushFront(plist *list, DataType d)
{
	assert(list != NULL);
	pnode newnode = CreateNode(d);
	pnode cur = *list;
	if (cur == NULL)
	{
		*list = newnode;
		newnode->_next = NULL;
	}
	else
	{
		*list = newnode;
		newnode->_next = cur;
	}
	return;
}

void PopFront(plist *list)
{
	assert(list != NULL);
	pnode cur = *list;
	if (cur == NULL)
	{
		return;
	}
	else if (cur->_next == NULL)
	{
		cur = cur->_next;
		free(cur);
		*list = NULL;
	}
	else
	{
		*list = cur->_next;
		free(cur);
		cur = NULL;
	}
	return;
}

void Destroy(plist  *list)
{
	pnode cur = *list;
	while (cur != NULL)
	{
		*list = cur->_next;
		cur = *list;
	}
	return;
}
void ShowList(plist list)
{
	pnode cur = list;
	while (cur != NULL)
	{
		printf("%d ", cur->_data);
		cur = cur->_next;
	}
	printf("\n");
}


void *product(void * _val)
{
	while (1)
	{
		sleep(1);
		//加鎖
		pthread_mutex_lock(&lock);
		int num = rand() % 100;
		Init(&listHead);
		PushFront(&listHead, num);
		printf("call consum:product success and the value is %d\n", num);
		//解鎖
		pthread_mutex_unlock(&lock);
		//喚醒等待目標變數的執行緒
		pthread_cond_signal(&need_product);
	}
}


void *consum(void *_val)
{
	while (1)
	{
		pthread_mutex_lock(&lock);
		while (listHead == NULL)
		{
			//等待目標條件變數,鎖使得pthread_cond_wait操作的原子性
			pthread_cond_wait(&need_product, &lock);
		}
		printf("call product:consum success and the value is %d\n", listHead->_data);
		PopFront(&listHead);
		ShowList(listHead);
		pthread_mutex_unlock(&lock);
	}
	return NULL;
}

int main()
{
	pthread_t t_product;
	pthread_t t_consum;
	pthread_create(&t_product, NULL, product, NULL);
	pthread_create(&t_consum, NULL, consum, NULL);
	//回收執行緒
	pthread_join(t_product, NULL);
	pthread_join(t_consum, NULL);
	return 0;
}