码迷,mamicode.com
首页 > 编程语言 > 详细

UNIX环境高级编程11.6线程同步

时间:2015-02-07 18:42:17      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

 

技术分享

 

技术分享

 

技术分享

 

技术分享

 

技术分享

 

// threads/mutex1.c 11-5
#include <pthread.h>
#include <stdlib.h>
#include <apue.h>

struct foo {
    int             f_count;
    pthread_mutex_t f_lock;
    int             f_id;
    /* ... more stuff here ... */
};

struct foo* foo_alloc(int id) /* allocate the object */
{
    foo* fp;

    if ((fp = (foo*)malloc(sizeof(foo))) != NULL)
    {
        fp->f_count = 1;
        fp->f_id = id;
        if (pthread_mutex_init(&fp->f_lock, NULL) != 0)
        {
            free(fp);
            return(NULL);
        }
        /* ... continue initialization ... */
    }
    return(fp);
}

void foo_hold(foo *fp) /* add a reference to the object */
{
    pthread_mutex_lock(&fp->f_lock);
    fp->f_count++;
    pthread_mutex_unlock(&fp->f_lock);
}

void foo_rele(foo* fp) /* release a reference to the object */
{
    pthread_mutex_lock(&fp->f_lock);
    if (--fp->f_count == 0)
    { /* last reference */
        pthread_mutex_unlock(&fp->f_lock);
        pthread_mutex_destroy(&fp->f_lock);
        free(fp);
    }
    else
    {
        pthread_mutex_unlock(&fp->f_lock);
    }
}


void* thr_fn(void* arg)
{
    printf("new thread: %lx\n", pthread_self());
    for (int i = 0; i < 90000000; i++)
    {
        foo_hold(static_cast<foo*>(arg));
    }

    return((void *)8888);
}

int main()
{
    pthread_t ntid;
    int err;
    void* ret;

    foo* pf = foo_alloc(1);

    err = pthread_create(&ntid, NULL, thr_fn, static_cast<void*>(pf));
    if (0 != err)
    {
        err_quit("can‘t create thread: %s\n", strerror(err));
    }
    printf("main thread: %lx\n", pthread_self());
    for (int i = 0; i < 90000000; i++)
    {
        foo_hold(static_cast<foo*>(pf));
    }

    err = pthread_join(ntid, &ret);
    if (err != 0)
    {
        err_quit("can‘t join with thread 1: %s\n", strerror(err));
    }
    printf("new thread exit code %d\n", (int)(long)ret);
    printf("pf->fcount = %d\n", pf->f_count);

    return 0;
}

 

技术分享

 

 

技术分享

UNIX环境高级编程11.6线程同步

标签:

原文地址:http://www.cnblogs.com/sunyongjie1984/p/4279122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!