⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 condmutex.c

📁 基于linux的系统编程程序
💻 C
字号:
/*condmutex.c*/
#include <stdlib.h>  
#include <stdio.h>  
#include <pthread.h>  
#include <errno.h>   

/*全局变量*/
int gnum = 0;
/*互斥量 */
pthread_mutex_t mutex;
/*条件变量*/
pthread_cond_t  cond;

/*声明线程运行服务程序*/
static void pthread_func_1 (void);   
static void pthread_func_2 (void);   

int main (void)   
{   
	/*线程的标识符*/
	pthread_t pt_1 = 0;   
	pthread_t pt_2 = 0;   
	int ret = 0;   
	
	/*互斥初始化*/
	pthread_mutex_init (&mutex, NULL); 
	/*条件变量初始化*/
	pthread_cond_init(&cond,NULL);
	/*分别创建线程1、2*/
	ret = pthread_create (&pt_1,			//线程标识符指针
		NULL,			//默认属性
		(void *)pthread_func_1,//运行函数
		NULL);   		//无参数
	if (ret != 0)   
	{   
		perror ("pthread_1_create");   
	}   
	
	ret = pthread_create (&pt_2, 			//线程标识符指针
		NULL,			//默认属性	
		(void *)pthread_func_2, //运行函数
		NULL);   		//无参数
	if (ret != 0)   
	{   
		perror ("pthread_2_create");   
	}   
	/*等待线程1、2的结束*/
	pthread_join (pt_1, NULL);   
	pthread_join (pt_2, NULL);   
	
	printf ("main programme exit!\n");  
	return 0;   
}   

/*线程1的服务程序*/
static void pthread_func_1 (void)   
{   
	int i = 0;   
	
	for (;;)   
	{   
		printf ("This is pthread1!\n");    
		pthread_mutex_lock(&mutex); /*获取互斥锁*/
		/*注意,这里以防线程的抢占,以造成一个线程在另一个线程sleep时多次访问互斥资源,所以sleep要在得到互斥锁后调用*/
		sleep (1);
		/*条件变量,当gnum<=3时,线程1自己挂起并且解锁,让线程2进去*/
		while (gnum <= 3) {
			pthread_cond_wait(&cond, &mutex);
		}
		/*当线程2调用pthread_cond_signal(&cond)时,线程1在这里重启*/
		/*临界资源*/
		gnum++;
		printf ("Thread1 add one to num:%d\n",gnum);
		pthread_mutex_unlock(&mutex); /*释放互斥锁*/
		
		
		
	}   
}   
/*线程2的服务程序*/ 
static void pthread_func_2 (void)   
{   
	int i = 0;   
	
	for (;;)   
	{   
		printf ("This is pthread2!\n"); 
		pthread_mutex_lock(&mutex); /*获取互斥锁*/
		/*注意,这里以防线程的抢占,以造成一个线程在另一个线程sleep时多次访问互斥资源,所以sleep要在得到互斥锁后调用*/
		sleep (1);
		/*临界资源*/
		gnum++;
		printf ("Thread2 add one to num:%d\n",gnum);
		/*当gnum == 4时,触发*/
		if (gnum == 4) 
			pthread_cond_signal(&cond);
		
		pthread_mutex_unlock(&mutex); /*释放互斥锁*/
		
	}   
	
	pthread_exit (0);   
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -