Chinaunix首页 | 论坛 | 博客
  • 博客访问: 800921
  • 博文数量: 489
  • 博客积分: 475
  • 博客等级: 下士
  • 技术积分: 3087
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-08 16:28
文章分类

全部博文(489)

文章存档

2013年(7)

2012年(301)

2011年(181)

分类:

2011-12-22 20:50:48

原文地址:线程同步(互斥量) 作者:luozhiyong131

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t mutex;
int x;

void thread1(void)
{
    while(x>0)
    {
        pthread_mutex_lock(&mutex);
        printf("thread 1 is running x=%dn",x);
        x--;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}

void thread2(void)
{
    while(x>0)
    {
        pthread_mutex_lock(&mutex);
        printf("thread 2 is running x=%dn",x);
        x--;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t id1,id2;
    int ret;
    ret = pthread_mutex_init(&mutex,NULL);
    if(ret!=0)
    {
        printf("pthread_mutex_init failedn");
        exit(1);
    }
    x=10;
    
    ret = pthread_create(&id1,NULL,(void *)&thread1,NULL);
    if(ret!=0)
    {
        printf("pthread_create 1 failedn");
        exit(1);
    }
    
    ret = pthread_create(&id2,NULL,(void *)&thread2,NULL);
    if(ret!=0)
    {
        printf("pthread_create 2 failedn");
        exit(1);
    }
    
    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    return 0;
}


阅读(289) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~