zoukankan      html  css  js  c++  java
  • Linux多线程的一个小例子

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <pthread.h>
    
    #define MAX_COUNT 9
    pthread_mutex_t mutex;	//互斥变量
    pthread_cond_t cond;	//条件变量
    int count = 0;
    
    void AddCount_Odd_Func(void);
    void AddCount_Even_Func(void);
    
    int main()
    {
    	int ret;
    	pthread_t odd_thread, even_thread;	//两个线程
    	pthread_attr_t thread_attr;			//线程的属性结构
    
    	count = 0;
    	pthread_mutex_init(&mutex, NULL);	//互斥变量的初始化
    	pthread_cond_init(&cond, NULL);		//条件变量的初始化
    	ret = pthread_attr_init(&thread_attr);	//属性结构体初始化
    	if (ret != 0)
    	{
    		perror("Attribute Creation Failed!");
    		exit(EXIT_FAILURE);
    	}
    
    	pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);	//设置线程分离状态的函数,PTHREAD_CREATE_DETACHED(分离线程):不需要创建线程的线程等待
    										//函数运行结束线程便终止,同时释放占用的系统资源
    	ret = pthread_create(&odd_thread, &thread_attr, (void *)&AddCount_Odd_Func, NULL);
    	if (ret != 0)
    	{
    		perror("Thread Creation Failed!");
    		exit(EXIT_FAILURE);
    	}
    	ret = pthread_create(&even_thread, &thread_attr, (void *)&AddCount_Even_Func, NULL);
    	if (ret != 0)
    	{
    		perror("Thread Creation Failed!");
    		exit(EXIT_FAILURE);
    	}
    
    	while (count < MAX_COUNT);
    	printf("Finished!
    ");
    	pthread_cond_destroy(&cond);		//销毁条件变量
    	pthread_mutex_destroy(&mutex);
    	return 0;
    }
    
    void AddCount_Odd_Func(void)
    {
    	pthread_mutex_lock(&mutex);
    	while (count < MAX_COUNT)
    	{
    		if (count % 2 == 1)
    		{
    			count++;
    			printf("AddCount_Odd_Func(): count = %d.
    ", count);
    			pthread_cond_signal(&cond);			//用来释放被阻塞在条件变量cond上的线程
    		}
    		else
    			pthread_cond_wait(&cond, &mutex);	//使线程阻塞在条件变量cond上
    	}
    	pthread_mutex_unlock(&mutex);
    }
    
    void AddCount_Even_Func(void)
    {
    	pthread_mutex_lock(&mutex);
    	while (count < MAX_COUNT)
    	{
    		if (count % 2 == 0)
    		{
    			count++;
    			printf("AddCount_Even_Func(): count = %d.
    ", count);
    			pthread_cond_signal(&cond);
    		}
    		else
    			pthread_cond_wait(&cond, &mutex);
    	}
    	pthread_mutex_unlock(&mutex);
    }

    gcc example.c -lpthread

    运行结果如下:


  • 相关阅读:
    C++后台开发校招面试常见问题
    算术表达式的前缀,中缀,后缀相互转换
    Redis键值对数据库的设计与实现
    C++经典面试题(最全,面中率最高)
    C++开发工程师面试题大合集
    C++中常用的设计模式
    C++中const修饰函数,函数参数,函数返回值的作用
    C++main函数的参数介绍以及如何在main函数前执行一段代码
    Windows系统下安装tensorflow+keras深度学习环境
    第十三周学习总结
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3293625.html
Copyright © 2011-2022 走看看