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

//已解决,参考最新的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.\n");
            free(lpFoo);
            return NULL;
        }
    }
    printf("Alloc a Foo.\n");
    return lpFoo;
}

bool DestoryFoo(foo* apFoo)
{
    pthread_mutex_lock(&apFoo->f_lock);
    if(--apFoo->f_count == 0)
    {
        printf("Now f_coount:%d.\n",apFoo->f_count);
        pthread_mutex_unlock(&apFoo->f_lock);
        pthread_mutex_destroy(&apFoo->f_lock);
        free(apFoo);
        printf("Destroy foo.\n");
        return true;
    }
    else
    {
        printf("Now f_coount:%d.\n",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.\n",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).\n",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);
}

  

相关文章:

  • 2021-11-13
  • 2021-07-08
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2021-09-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-01
  • 2021-12-27
  • 2021-06-24
  • 2021-11-07
相关资源
相似解决方案