您的位置:首页 > 其它

线程间的同步----利用信号量来实现

2015-04-27 20:49 183 查看
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

sem_t bin_sem;
void *thread_funtion(void *arg);
char work_area[1024];

int main() {
pthread_t a_thread;
int res;
void *thread_result;
res = sem_init(&bin_sem, 0, 0);
if(res != 0) {
perror("初始化信号量失败");
exit(EXIT_FAILURE);
}
res = pthread_create(&a_thread, NULL, thread_funtion, NULL);
if(res != 0) {
perror("线程创建失败");
exit(EXIT_FAILURE);
}
printf("请输入要传送的信息,输入'end'退出\n");
while(strncmp("end", work_area, 3) != 0) {
fgets(work_area, 1024, stdin);
sem_post(&bin_sem);				// 将信号量加1
}
printf("\n等待线程结束...\n");
res = pthread_join(a_thread, &thread_result);                // 等待线程结束
if (res != 0) {                                                   // 判断结束线程是否有错误
perror("线程结束失败");
exit(EXIT_FAILURE);
}
printf("线程结束\n");
sem_destroy(&bin_sem);                           			 // 清除信号量                                                    // 清除信号量
exit(EXIT_SUCCESS);
}

void *thread_funtion(void *arg) {
sem_wait(&bin_sem);				// 等待信号量变化,将信号量减1
while(strncmp("end", work_area, 3) != 0) {			// 判断收到的信息是否是“end”
printf("收到%lu个字符\n", strlen(work_area) - 1);          // 输出收到信息的字符数量
sem_wait(&bin_sem);			// 等待信号量变化,将信号量减1
}
pthread_exit(NULL);					// 结束线程
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: