Chinaunix首页 | 论坛 | 博客
  • 博客访问: 279427
  • 博文数量: 109
  • 博客积分: 2116
  • 博客等级: 大尉
  • 技术积分: 1062
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-22 15:38
文章分类

全部博文(109)

文章存档

2013年(2)

2011年(16)

2010年(90)

2009年(1)

我的朋友

分类: LINUX

2010-07-09 14:45:14

上次用互斥锁,这次用信号量同步机制来实现同步。

系统函数有:sem_init, sem_wait, sem_trywait, sem_post, sem_getvalue, sem_destroy.

源代码来自华清远见:

#include

#include

#include

#include

 

#define THREAD_NUMBER   3

#define REPEAT_NUMBER   3

#define DELAY_TIME_LEVELS   10.0

sem_t sem[THREAD_NUMBER];

 

void *thrd_func(void *arg)

{

    int thrd_num = (int)arg;

    int delay_time = 0;

    int count = 0;

 

    sem_wait(&sem[thrd_num]);//P操作   

    printf("Thread %d is starting\n", thrd_num);

    for(count = 0; count < REPEAT_NUMBER; count++)

    {

        delay_time = (int) (rand() *DELAY_TIME_LEVELS/(RAND_MAX) + 1);

        sleep(delay_time);

        printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time);

    }

    printf("Thread %d finished\n", thrd_num);

    pthread_exit(NULL);

}

 

int main()

{

    pthread_t thread[THREAD_NUMBER];

    int no = 0, res;

    void *thrd_ret;

 

    srand(time(NULL));

    for(no = 0; no < THREAD_NUMBER; no++)

    {

        res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);

        if(res != 0)

        {

            printf("Create thread %d failed\n", no);

            exit(res);

        }

    }

    printf("Create threads success\nWaiting for threads to finish..\n");

 

    sem_post(&sem[THREAD_NUMBER - 1]);//对最后创建的线程信号量进行V操作

    for( no = THREAD_NUMBER - 1; no >= 0; no--)

    {

        res = pthread_join(thread[no], &thrd_ret);

        if(!res)

        {

            printf("Thread %d joined\n", no);

        }

        else

        {

            printf("Thread %d join failed\n", no);

        }

        sem_post(&sem[(no + THREAD_NUMBER -1) % THREAD_NUMBER]);//V操作

    }

   

    for(no = 0; no < THREAD_NUMBER; no++)

    {

        sem_destroy(&sem[no]);//删除信号量

    }

    return 0;

}

编译运行,结果如下:

可以看出3个线程运行是与创建的顺序相反的,同样我们用信号量实现了线程的同步。

阅读(1125) | 评论(0) | 转发(1) |
0

上一篇:线程互斥锁

下一篇:多线程实验

给主人留下些什么吧!~~