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

笔记2 linux多线程 读写锁

时间:2015-09-25 16:02:44      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

//read write lock
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

struct test
{
    char a[10];
    char b[10];
    char c[10];
}yb = {"111","222","33333"};

static int j=0;

pthread_rwlock_t mutex_1;


void Print1(struct test *arg)
{
    pthread_rwlock_rdlock(&mutex_1);
    printf("a=%s,b=%s,c=%s,d=%X,j=%d\n",arg->a,arg->b,arg->c,pthread_self(),j++);
    sleep(2);
    pthread_rwlock_unlock(&mutex_1);
    pthread_exit((void *)j);
    printf("Never Coming.\n");
}

struct test *Print2(struct test *arg)
{
    pthread_rwlock_wrlock(&mutex_1);
    struct test *p = NULL;
    p = arg;
    memcpy(p->a,"fff",3);
    memcpy(p->b,"ggg",3);
    memcpy(p->c,"ttt",3);
    pthread_rwlock_unlock(&mutex_1);
    pthread_exit((void *)0);
}


int main()
{
    pthread_t pid1,pid2,pid3,pid4;
    void *set;

    pthread_rwlock_init(&mutex_1,NULL);

    pthread_create(&pid1,NULL,&Print1,&yb);
    sleep(1);
    pthread_create(&pid2,NULL,&Print2,&yb);
    pthread_create(&pid3,NULL,&Print1,&yb);
    sleep(10);
    pthread_create(&pid4,NULL,&Print1,&yb);

    pthread_join(pid1,&set);
    printf("pid1 exit coed %d\n",(int)set);
    pthread_join(pid2,&set);
    printf("pid2 exit coed %d\n",(int)set);
    pthread_join(pid3,&set);
    printf("pid3 exit coed %d\n",(int)set);
    pthread_join(pid4,&set);
    printf("pid4 exit coed %d\n",(int)set);

    pthread_rwlock_destroy(&mutex_1);
    sleep(1);
    return 0;
}

 

笔记2 linux多线程 读写锁

标签:

原文地址:http://www.cnblogs.com/sherlockhomles/p/4838318.html

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