1.在循环打印倒置那题的条件基础上用信号量实现,打印一次,倒置一次.
a.提示: 用两个信号量,一个初始化为1,另外一个初始化为0
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
char buf[] = "1234567";
//sem1读取,sem2倒置
sem_t sem1, sem2;
//读取打印
void* callBack1(void* arg)
{
while(1)
{
// p,等待读取信号量
if(sem_wait(&sem1) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
printf("%s\n", buf);
// v,发送倒置信号量
if(sem_post(&sem2) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
//倒置
void* callBack2(void* arg)
{
int i, j;
char temp = 0;
int len = strlen(buf);
while(1)
{
// p,等待倒置信号量
if(sem_wait(&sem2) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
for(i = 0, j = len - 1; i < j; i++, j--)
{
temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
// v,发送读取信号量
if(sem_post(&sem1) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem1, 0, 1);
sem_init(&sem2, 0, 0);
pthread_t tid1, tid2;
if(pthread_create(&tid1, NULL, callBack1, NULL) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
if(pthread_create(&tid2, NULL, callBack2, NULL) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
2.创建两个线程,要求一个线程从文件中读取数据,另一个线程将读取到的数据打印到终端,类似cat
个文件。文件cat完毕后,要结束进程
a读到一次数据,打印一次数据
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <semaphore.h>
#define N 100
char buf[N];
sem_t sem1, sem2;
// 读取数据
void* callBack1(void* arg)
{
FILE* fp = fopen("./13_sem.c", "r");
if (NULL == fp)
{
perror("fopen");
pthread_exit(NULL);
}
while (fgets(buf, N, fp) != NULL)
{
if (sem_post(&sem1) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
if (sem_wait(&sem2) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
}
fclose(fp);
if (sem_post(&sem1) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
pthread_exit(NULL);
}
// 打印
void* callBack2(void* arg)
{
while (1)
{
if (sem_wait(&sem1) < 0)
{
perror("sem_wait");
pthread_exit(NULL);
}
printf("%s", buf);
if (sem_post(&sem2) < 0)
{
perror("sem_post");
pthread_exit(NULL);
}
}
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
sem_init(&sem1, 0, 0);
sem_init(&sem2, 0, 0);
pthread_t tid1, tid2;
if (pthread_create(&tid1, NULL, callBack1, NULL) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
if (pthread_create(&tid2, NULL, callBack2, NULL) != 0)
{
fprintf(stderr, "pthread_create failed __%d__\n", __LINE__);
return -1;
}
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}