pthread库学习(2): 线程的同步,使用信号量

先看下面这段程序,主线程创建了三个线程,每个线程中均有一个打印语句。

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

  void *thread_a(void *in)

{

printf("I am thread_a/n");

pthread_exit((void *)0);

}

 

void *thread_b(void *in)

{

printf("I am thread_b/n");

pthread_exit((void *)0);

}

 

void *thread_c(void *in)

{

    printf("I am thread_c/n");

pthread_exit((void *)0);

}

 

int main()

{

    pthread_t a,b,c;  /* thread id a, b, c*/

    int val;         /* used for function return result */

 

    /* create thread a, b, c */

    pthread_create(&a, NULL, thread_a, (void *)0);

    pthread_create(&b, NULL, thread_b, (void *)0);

    pthread_create(&c, NULL, thread_c, (void *)0);

 

    /* main thread waits for termination of a,b,c */

    pthread_join(a, (void **)0);

    pthread_join(b, (void **)0);

    pthread_join(c, (void **)0);

 

    printf("Main thread is over/n");

    return 0;

}

在Linux下进行编译: gcc -o My_Thread My_Thread.c ./MyThread
得到的输出:
 I am thread_a
I am thread_b
I am thread_c
Main thread is over

现在我们希望线程C的最先打印,然后线程B打印,最后线程A打印。即三个线程之间的打印有一定的先后关系。看下面程序:

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

sem_t sem1;

sem_t sem2;

void *thread_a(void *in)

{

    sem_wait(&sem1);       /* wait for sem1 */

    printf("I am thread_a/n");

    pthread_exit((void *)0);

}

 

void *thread_b(void *in)

{

    sem_wait(&sem2);       /* wait for sem2 */

    printf("I am thread_b/n");

    sem_post(&sem1);       /* increase sem1 by 1, make thread_a run*/

    pthread_exit((void *)0);

}

 

void *thread_c(void *in)

{

    printf("I am thread_c/n");

    sem_post(&sem2);      /* increase sem2 by 1, make thread_b run*/

    pthread_exit((void *)0);

}

 

int main()

{

    pthread_t a,b,c;  /* thread id a, b, c*/

    int val;         /* used for function return result */

 

    /* init sem1 sem2 to 0 , any thread waits for it will be blocked*/

    sem_init(&sem1, 0, 0);

sem_init(&sem2, 0, 0);

   

/* create thread a, b, c */

pthread_create(&a, NULL, thread_a, (void *)0);

pthread_create(&b, NULL, thread_b, (void *)0);

pthread_create(&c, NULL, thread_c, (void *)0);

 

    /* main thread waits for termination of a,b,c */

    pthread_join(a, (void **)0);

    pthread_join(b, (void **)0);

    pthread_join(c, (void **)0);

 

    /* destroy sem1 sem2 */

    sem_destroy(&sem1);

    sem_destroy(&sem2);

 

    printf("Main thread is over/n");

    return 0;

}

gcc -o My_thread1 My_thread1.c -lpthread
./My_thread1
I am thread_c
I am thread_b
I am thread_a
Main thread is over

可以见到,线程的执行顺序已经改变。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值