Chinaunix首页 | 论坛 | 博客
  • 博客访问: 650242
  • 博文数量: 121
  • 博客积分: 4034
  • 博客等级: 上校
  • 技术积分: 1439
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-28 12:42
文章分类

全部博文(121)

文章存档

2017年(8)

2016年(10)

2013年(2)

2012年(3)

2011年(18)

2010年(80)

分类: LINUX

2010-10-21 23:51:16

pthread_create简单使用


#include
#include
#include
#include
#include

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int lock_var;
time_t end_time;


void thread1(void *arg)
{
    int i = 0;
    while(time(NULL) < end_time)
    {
        if(pthread_mutex_lock(&mutex) != 0)
        {
            printf("pthread_mutex_lock error!!\n");
        }
        else
            printf("pthread1:pthread1 lock the time.\n");
        for(i=0;i<2;i++)
        {
            sleep(1);
            lock_var++;
        }   
        if(pthread_mutex_unlock(&mutex) != 0)
        {
            printf("pthread_mutex_unlock error!!\n");
        }
        else
            printf("pthread1:pthread1 unlock the time.\n");

        sleep(1);
    }
}

void thread2(void *arg)
{
    int nolock = 0;
    int ret;
    while(time(NULL) < end_time)
    {
        ret = pthread_mutex_trylock(&mutex);
        if(ret == 16)
            printf("pthread2:the time is locked by pthread1.\n");
        else
        {
            if(ret != 0)
            {
                printf("pthread_mutex_trylock error!!\n");
                pthread_exit(NULL);
            }   
            else
                printf("pthread2:pthread2 got lock.the time is %d.\n",lock_var);
           
                if(pthread_mutex_unlock(&mutex) != 0)
                    printf("pthread_mutex_unlock error!!\n");
                else
                    printf("pthread2:pthread2 unlock the time.\n");
       
        }
        sleep(3);
    }
}

int main(void)
{
    pthread_t id1,id2;
    pthread_t mon_th_id;
    int ret;

    end_time = time(NULL) + 20;

    pthread_mutex_init(&mutex,NULL);

    ret = pthread_create(&id1,NULL,(void*)thread1,NULL);
    if(ret != 0)
    {
        printf("Create pthread1 error!\n");
        return 0;
    }
   
    ret = pthread_create(&id2,NULL,(void*)thread2,NULL);
    if(ret != 0)
    {
        printf("Create pthread2 error!\n");
        return 0;
    }
    pthread_join(id1,NULL);
    pthread_join(id2,NULL);
    printf("two pthread is exit!\n");
    return 0;
}

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