pthread库学习(2): 线程的同步,使用信号量
来源:互联网 发布:淘宝帮派活动有用吗 编辑:程序博客网 时间:2024/06/03 20:09
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
{
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
可以见到,线程的执行顺序已经改变。
- pthread库学习(2): 线程的同步,使用信号量
- pthread库学习(2): 线程的同步,使用信号量
- 线程同步信号量的使用
- 线程同步--使用信号量
- 线程同步:信号量Semaphore的使用
- 线程的同步--信号量
- 使用信号量机制同步线程
- pthread库学习(1): 线程的创建
- C++ pthread 信号量及detach的使用
- windows下pthread线程库的使用
- 基于信号量的线程同步
- 基于信号量的线程同步
- 线程的同步(四)---信号量
- Linux线程的信号量同步
- Linux线程的信号量同步
- pthread线程同步机制
- pthread线程同步机制
- 使用信号量进行线程间同步
- 对象数据库(ODBMS) db4o试用(Java version)
- (转贴)C#资源
- 重新再学习C++的练习
- [Flash Component] Movie Controller
- googl这么热,我也来说点啥
- pthread库学习(2): 线程的同步,使用信号量
- 重温classpath.
- LZW Data Compression
- What is bzip2?
- [Flash Component] FlashTextEditor
- vb考试
- [书籍]《Programming Flash Communication Server》
- SQL Server 2000的安全配置
- [学习资源] Macromedia的信息交流平台