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

    运行结果如下:


  • 相关阅读:
    Problem about objc_exception_throw
    Change mime Types for mac's default apache
    重启Mac上的Apache服务
    通过无线网安装自己打包的ipa文件
    How to cancel selection for TreePanel(GXT)
    使用Jsoup获取网页内容超时设置
    HTML Meta, http-equiv, Refresh
    线上redis服务内存异常分析。
    C++/CLI 本地字符串和托管字符串之间的转换
    DWF Toolkit on Microsoft Windows
  • 原文地址:https://www.cnblogs.com/suncoolcat/p/3293625.html
Copyright © 2011-2022 走看看