zoukankan      html  css  js  c++  java
  • 线程同步机制之互斥锁通信机制

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #include <string.h>
    
    void *thread_function(void *arg);
    pthread_mutex_t work_mutex;
    #define WORK_SIZE 1024
    char work_area[WORK_SIZE];
    int time_to_exit=0;
    int main(int argc, char *argv[])
    {
        int res;
        pthread_t a_thread;
        void *thread_result;
        res=pthread_mutex_init(&work_mutex,NULL);
        if(res!=0)
        {
            printf("Mutex initialization failed
    ");
            exit(EXIT_FAILURE);
        }
        res=pthread_create(&a_thread,NULL,thread_function,NULL);
        if(res!=0)
        {
            printf("Thread creation failed
    ");
            exit(EXIT_FAILURE);
        }
        pthread_mutex_lock(&work_mutex);
        printf("Input some text. Enter 'end' to finish
    ");
        while(!time_to_exit)
        {
            fgets(work_area,WORK_SIZE,stdin);
            pthread_mutex_unlock(&work_mutex);
            while(1)
            {
                pthread_mutex_lock(&work_mutex);
                if(work_area[0]!='')
                {
                    pthread_mutex_unlock(&work_mutex);
                    sleep(1);
                }
                else 
                    break;
            }
        }
        pthread_mutex_unlock(&work_mutex);
        printf("
    Waitting for thread to finish...
    ");
        res=pthread_join(a_thread,&thread_result);
        if(res!=0)
        {
            printf("Thread join failed
    ");
            exit(EXIT_FAILURE);
        }
        printf("Thread joined
    ");
        pthread_mutex_destroy(&work_mutex);
        exit(EXIT_SUCCESS);
        return 0;
    }
    
    void *thread_function(void *arg)
    {
        sleep(1);
        pthread_mutex_lock(&work_mutex);
        while(strncmp("end",work_area,3)!=0)
        {
            printf("You input %d characters
    ",strlen(work_area)-1);
            printf("the character is: %s",work_area);
            work_area[0]='';
            pthread_mutex_unlock(&work_mutex);
            sleep(1);
            pthread_mutex_lock(&work_mutex);
            while(work_area[0]=='')
            {
                pthread_mutex_unlock(&work_mutex);
                sleep(1);
                pthread_mutex_lock(&work_mutex);
            }
    
        }
        time_to_exit=1;
        work_area[0]='';
        pthread_mutex_unlock(&work_mutex);
        pthread_exit(0);
    }

  • 相关阅读:
    ylbtech-dbs-m-YinTai(银泰网)
    ylbtech-memorandum(备忘录)-数据库设计
    设计工作-Axure
    RegexHelper
    convert image to base64
    MVC Movie App
    ASP.NET MVC file download sample
    MVC架构、WebForm与MVC对比
    第2章 数字之魅——子数组之和的最大值(二维)
    第2章 数字之魅——求数组的子数组之和的最大值
  • 原文地址:https://www.cnblogs.com/lakeone/p/3789639.html
Copyright © 2011-2022 走看看