//创建两个线程,实现将一个文件的内容打印到终端上,类似cat一个文件
//一个线程读取文件中的内容
//另一个线程将读取到的内容打印到终端上。
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>
sem_t sem1, sem2;
char c = 0;
void* callBack1(void* arg) {
while (1) {
sem_wait(&sem1);
if (c == EOF) break;
printf("%c", c);
sem_post(&sem2);
}
pthread_exit(NULL);
}
void* callBack2(void* arg)
{
FILE* fd_r = fopen("./print_mutex.c", "r");
if (NULL==fd_r )
{
perror("fopen");
return NULL;
}
while (1)
{
sem_wait(&sem2);
int ret = fread(&c, sizeof(char), 1,fd_r);
if (ret == 0 || c == EOF)
{
c = EOF;
break;
}
sem_post(&sem1);
}
fclose(fd_r);
pthread_exit(NULL);
}
int main(int argc, const char* argv[]) {
if (sem_init(&sem1, 0, 0) < 0) {
perror("sem_init");
return -1;
}
if (sem_init(&sem2, 0, 1) < 0) {
perror("sem_init");
return -1;
}
pthread_t tid1, tid2;
if (pthread_create(&tid1, NULL, callBack1, NULL) != 0) {
fprintf(stderr, "pthread_create failed %d\n", __LINE__);
return -1;
}
pthread_detach(tid1);
if (pthread_create(&tid2, NULL, callBack2,NULL) != 0) {
fprintf(stderr, "pthread_create failed %d\n", __LINE__);
return -1;
}
pthread_join(tid2, NULL);
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}
```c
//现有ID号为a b c的三个线程,每个线程的任务都是循环打印自己id号,要求打印的顺序为abc
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define THREAD_COUNT 3
sem_t sem[THREAD_COUNT]; // 信号量数组,保证线程执行的先后顺序
int next_thread = 0; // 下一个应该执行的线程的标识符
void* print_thread(void* arg) {
int id = *(int*)arg; // 线程 id
while (1) {
sem_wait(&sem[id]); // 等待自己的信号量
printf("%c", id + 'a'); // 打印对应的字母
fflush(stdout);
sem_post(&sem[next_thread]); // 发送下一个线程的信号量
next_thread = (next_thread + 1) % THREAD_COUNT; // 更新下一个执行的线程
}
return NULL;
}
int main(int argc, const char *argv[]) {
pthread_t tid[THREAD_COUNT];
int id[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; i++) {
id[i] = i;
if(sem_init(&sem[i], 0, 0) < 0) {
perror("sem_init");
return -1;
}
pthread_create(&tid[i], NULL, print_thread, (void*)&id[i]);
}
sem_post(&sem[0]); // 发送第一个线程的信号量
pthread_join(tid[0], NULL);
for (int i = 0; i < THREAD_COUNT; i++) {
sem_destroy(&sem[i]);
}
return 0;
}
5.10作业
于 2023-05-11 00:03:43 首次发布