Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1250309
  • 博文数量: 247
  • 博客积分: 5587
  • 博客等级: 大校
  • 技术积分: 2060
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-24 13:27
文章分类
文章存档

2012年(101)

2011年(44)

2010年(102)

分类:

2010-11-07 00:42:27

现举个简单的例子来Linux多线程编程,熟悉互斥锁和条件变量对共享资源的保护。首先,建立两个线程,然后线程1用来输出非3的倍数的值,线程2用来输出3的倍数的值。

 

#include 

#include 

#include 

#include 

 

pthread_mutex_t mutex;

pthread_cond_t cond;

int i=0;

 

void *thread1()

{

       while (i < 9)

       {

              pthread_mutex_lock(&mutex);

              i++;

             

              /*如果条件满足,唤醒线程2*/

              if (i%3 == 0)

                     pthread_cond_signal(&cond);

              else

                     printf("thread1:%d\n", i);        

              pthread_mutex_unlock(&mutex);

              sleep(1);

       }

       return NULL;

}

 

void *thread2()

{

       while(i < 9)

       {

              pthread_mutex_lock(&mutex);

 

              /*如果条件不满足,线程自己挂起并且解锁*/

              while (i%3 != 0)

                     pthread_cond_wait(&cond, &mutex);

             

              /*本线程被唤醒后,在此接着执行*/

              printf("thread2:%d\n", i);

              pthread_mutex_unlock(&mutex);

              sleep(1);

       }

       return NULL;

}

 

int main()

{

       pthread_t t_1;

       pthread_t t_2;

      

       pthread_mutex_init(&mutex, NULL);

       pthread_cond_init(&cond, NULL);

 

       int ret;

       ret = pthread_create(&t_1, NULL, thread1, NULL);

       if(ret != 0)

              printf ("Create pthread1 error!\n");

       ret = pthread_create(&t_2, NULL, thread2, NULL);

       if(ret != 0)

              printf ("Create pthread2 error!\n");

       pthread_join(t_1, NULL);

       pthread_join(t_2, NULL);

 

       pthread_mutex_destroy(&mutex);

       pthread_cond_destroy(&cond);

 

       return 0;

}

 

# gcc –Wall –g –lpthread thread.c –o thread.exe

# ./thread.exe

 

运行结果:

thread1:1

thread1:2

thread2:3

thread1:4

thread1:5

thread2:6

thread1:7

thread1:8

thread2:9

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