作业1
题目
结果
代码
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
// 输出屏幕
void print_data()
{
char buf[1024];
char ch;
while (1) {
fgets(buf, sizeof(buf), stdin);
if (!strncmp(buf, "quit", 4))
break;
fputs(buf, stdout);
}
}
// 子线程
void *thread_func(void *arg)
{
char *p = "0x78";
while (1) {
printf("child thread is running\n");
print_data();
pthread_exit(p);
}
}
int main(int argc, char const *argv[])
{
pthread_t tid;
int ret;
int cnt = 0;
char *retval = NULL;
// 开启子线程
ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
errno = ret;
perror("pthread_create()");
return -1;
}
// 主线程
while (1) {
printf("%d====================\n", cnt++);
printf("main thread is running\n");
sleep(1);
pthread_join(tid, (void **)&retval);
printf("%s\n", retval);
}
return 0;
}
作业2
题目
结果
代码
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
pthread_t tid; // 读线程
pthread_t tid2; // 写线程
// 读文件
void read_file(int fd)
{
char buf[1024];
int n;
while (1) {
memset(buf, 0, sizeof(buf));
n = read(fd, buf, sizeof(buf));
if (n == 0) {
continue;
}
write(STDOUT_FILENO, buf, sizeof(buf));
}
}
// 写文件
void write_file(int fd)
{
char buf[1024];
int n;
while (1) {
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
if (!strncmp(buf, "quit", 4)) {
break;
}
n = write(fd, buf, sizeof(buf));
lseek(fd, -n, SEEK_CUR);
}
}
// 读线程
void *read_thread(void *arg)
{
int fd = *(int *)arg;
printf("read_thread is running\n");
while (1) {
sleep(2);
read_file(fd);
}
}
// 写线程
void *write_thread(void *arg)
{
int fd = *(int *)arg;
printf("write_thread is running\n");
while (1) {
write_file(fd);
sleep(1);
pthread_cancel(tid2);
pthread_exit(NULL);
}
}
int main(int argc, char const *argv[])
{
int ret; // 读线程
int ret2; // 写线程
int fd;
char *retval = NULL;
fd = open(argv[1], O_RDWR | O_CREAT | O_TRUNC, 0666);
// 开启子线程
ret = pthread_create(&tid, NULL, read_thread, (void *)&fd);
ret2 = pthread_create(&tid2, NULL, write_thread, (void *)&fd);
if (ret != 0 || ret2 != 0) {
errno = ret;
perror("pthread_create()");
return -1;
}
// 主线程
printf("main thread is running\n");
while (1) {
pthread_join(tid, (void **)&retval);
sleep(1);
}
close(fd);
return 0;
}