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);
}

  

原文地址:https://www.cnblogs.com/xiangshancuizhu/p/3334169.html