zoukankan      html  css  js  c++  java
  • linux线程学习

    按照书上写的,不知道为什么有问题:

    //已解决,参考最新的blog,哈哈

    #include <stdlib.h>
    #include <pthread.h>
    #include <stdio.h>
    #include <unistd.h>
    
    struct foo
    {
        int f_count;
        pthread_mutex_t f_lock;
    };
    struct foo* AllocFoo()
    {
        foo* lpFoo = (foo*)malloc(sizeof(struct foo));
        if(NULL != lpFoo)
        {
            lpFoo->f_count = 1;
            if(0 != pthread_mutex_init(&lpFoo->f_lock,NULL))
            {
                printf("pthread_mutex_init error.
    ");
                free(lpFoo);
                return NULL;
            }
        }
        printf("Alloc a Foo.
    ");
        return lpFoo;
    }
    
    bool DestoryFoo(foo* apFoo)
    {
        pthread_mutex_lock(&apFoo->f_lock);
        if(--apFoo->f_count == 0)
        {
            printf("Now f_coount:%d.
    ",apFoo->f_count);
            pthread_mutex_unlock(&apFoo->f_lock);
            pthread_mutex_destroy(&apFoo->f_lock);
            free(apFoo);
            printf("Destroy foo.
    ");
            return true;
        }
        else
        {
            printf("Now f_coount:%d.
    ",apFoo->f_count);
            pthread_mutex_unlock(&apFoo->f_lock);
            return false;
        }
    }
    
    void HoldFoo(foo* apFoo)
    {
        pthread_mutex_lock(&apFoo->f_lock);
        ++apFoo->f_count;
        printf("Now f_coount:%d.
    ",apFoo->f_count);
        pthread_mutex_unlock(&apFoo->f_lock);
    }
    
    void PrintTids(const char* s);
    
    void* ThreadFun(void* Arg)
    {
        PrintTids("");
        foo* lpFoo = (foo*)Arg;
        for(int i=0;i<5;++i)
        {
            HoldFoo(lpFoo);
        }
    }
    void PrintTids(const char* s)
    {
        pid_t lPid = getpid();
        pthread_t lTid = pthread_self();
        printf("%s pid:%u,tid:%u (0x%x).
    ",s,(unsigned int)lPid
               , (unsigned int)lTid,(unsigned int)lTid);
    }
    int main()
    {
        foo* lpFoo = AllocFoo();
        pthread_t lTid = 0;
        int lErr = pthread_create(&lTid,NULL,ThreadFun,NULL);
        if(0 != lErr)
        {
            exit(1);
        }
        printf("main thread");
        //HoldFoo(lpFoo);
        bool lIsDestory = false;
        do
        {
            lIsDestory = DestoryFoo(lpFoo);
        }while(!lIsDestory);
    }
    

      

  • 相关阅读:
    HDFS常用命令总结
    mac 安装zmap
    使用scrapy-redis搭建分布式爬虫环境
    xpath选择兄弟节点、返回上一级和选择多个属性
    什么是套接字(Socket)
    socket编程——一个简单的例子
    python之 __getattr__、__getattr__、__getitem__、__setitem__ 使用
    如何快速转载文章
    如何让类也变成可以迭代的对象
    leecode 第二题 简单
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/3334169.html
Copyright © 2011-2022 走看看