pthread库学习(2): 线程的同步,使用信号量
来源:互联网 发布:杭州网络推广公司 编辑:程序博客网 时间:2024/06/05 04:31
#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);return NULL;}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);return NULL;}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);return NULL;}int main(){pthread_t a,b,c; /* thread id a, b, c*//* 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
可以见到,线程的执行顺序已经改变。
转自 http://blog.csdn.net/direstrait/article/details/566716
- pthread库学习(2): 线程的同步,使用信号量
- pthread库学习(2): 线程的同步,使用信号量
- 线程同步信号量的使用
- 线程同步--使用信号量
- 线程同步:信号量Semaphore的使用
- 线程的同步--信号量
- 使用信号量机制同步线程
- pthread库学习(1): 线程的创建
- C++ pthread 信号量及detach的使用
- windows下pthread线程库的使用
- 基于信号量的线程同步
- 基于信号量的线程同步
- 线程的同步(四)---信号量
- Linux线程的信号量同步
- Linux线程的信号量同步
- pthread线程同步机制
- pthread线程同步机制
- 使用信号量进行线程间同步
- delete与delete[]的区别和使用方法
- PO等-对这些缩写详细介绍:PO BO VO DTO POJO DAO概念及其作用(附转换图)
- c++中的new关键字
- Oracle EBS中查询Profile的各种SQL
- Workmake所用W语言介绍
- pthread库学习(2): 线程的同步,使用信号量
- js操作文件
- ffmpeg 编译指令的理解
- pthread_cleanup_push() pthread_cleanup_pop()
- 2012.06.11
- 彻底理解面向对象的多态
- 黑马程序员-----String
- 关于窗口
- SQL SERVER 2008 安装 问题