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

    运行结果如下:


  • 相关阅读:
    Spark
    升级测试数据迁移数据库版本不兼容的问题:mysql5.7 timestamp默认值0000-00-00 00:00:00 报错
    Redis
    批处理引擎MapReduce
    分布式协调服务ZooKeeper
    分布式列式存储系统Kudu
    Python入门学习笔记9:Python高级语法与用法-枚举、函数式编程<闭包>
    Python入门学习笔记8:正则表达式与JSON
    Python入门学习笔记7:面向对象
    Python入门学习笔记6:函数
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3293625.html
Copyright © 2011-2022 走看看