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

来源:互联网 发布:淘宝帮派活动有用吗 编辑:程序博客网 时间:2024/06/03 20:09
先看下面这段程序,主线程创建了三个线程,每个线程中均有一个打印语句。

#include <stdio.h>

#include <pthread.h>

#include <semaphore.h>

 void *thread_a(void *in)

{

printf("Iam thread_a/n");

pthread_exit((void*)0);

}

 

void *thread_b(void *in)

{

printf("Iam 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 forfunction 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);       /* waitfor sem1 */

   printf("I am thread_a/n");

   pthread_exit((void *)0);

}

 

void *thread_b(void *in)

{

   sem_wait(&sem2);       /* waitfor 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 forfunction 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 threada, 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

可以见到,线程的执行顺序已经改变。
原创粉丝点击