1、信号量同步
/*
============================================================================
Name : Test.c
Author : wangchuan
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
sem_t bin_sem;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
void *thread_function(void *arg)
{
sem_wait(&bin_sem);
while(strncmp("end",work_area,3)!=0){
printf("收到%d个字符\n",strlen(work_area)-1);
sem_wait(&bin_sem);
}
pthread_exit(NULL);
}
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res=sem_init(&bin_sem,0,0);
if(res!=0){
perror("初始化信号量失败");
exit(EXIT_FAILURE);
}
res= pthread_create(&a_thread,NULL,thread_function,NULL);
if(res!=0){
perror("线程创建失败");
exit(EXIT_FAILURE);
}
printf("请输入要传送的信息,输入'end'退出\n");
while(strncmp("end",work_area,3)!=0){
fgets(work_area,WORK_SIZE,stdin);
sem_post(&bin_sem);
}
printf("等待线程结束...\n");
res=pthread_join(a_thread,&thread_result);
if(res!=0){
perror("等待线程结束失败");
exit(EXIT_FAILURE);
}
printf("线程结束\n");
sem_destroy(&bin_sem);
exit(EXIT_SUCCESS);
return 0;
}
2、互斥量同步
/*
============================================================================
Name : Test.c
Author : wangchuan
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
pthread_mutex_t work_mutex;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit=0;
void *thread_function(void *arg)
{
sleep(1);
pthread_mutex_lock(&work_mutex);
while(strncmp("end",work_area,3)!=0){
printf("收到%d个字符\n",strlen(work_area)-1);
work_area[0]='\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while(work_area[0]=='\0'){
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit=1;
work_area[0]='\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res=pthread_mutex_init(&work_mutex,NULL);
if(res!=0){
perror("初始化互斥量失败");
exit(EXIT_FAILURE);
}
res= pthread_create(&a_thread,NULL,thread_function,NULL);
if(res!=0){
perror("线程创建失败");
exit(EXIT_FAILURE);
}
pthread_mutex_lock(&work_mutex);
printf("请输入要传送的信息,输入'end'退出\n");
while(!time_to_exit){
fgets(work_area,WORK_SIZE,stdin);
pthread_mutex_unlock(&work_mutex);
while(1){
pthread_mutex_lock(&work_mutex);
if(work_area[0]!='\0'){
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else break;
}
}
pthread_mutex_unlock(&work_mutex);
printf("等待线程结束...\n");
res=pthread_join(a_thread,&thread_result);
if(res!=0){
perror("等待线程结束失败");
exit(EXIT_FAILURE);
}
printf("线程结束\n");
pthread_mutex_destroy(&work_mutex);
exit(EXIT_SUCCESS);
return 0;
}