gpt4 book ai didi

c - 将 UNIX 管道与 C 一起使用

转载 作者:行者123 更新时间:2023-11-30 16:03:35 25 4
gpt4 key购买 nike

我需要创建 6 个线程来同时执行任务(递增/递减数字),直到整数变为 0。我应该只使用 UNIX 命令(具体来说是管道),但我无法得到我的了解管道如何工作,或者如何实现这个程序。

这个整数可以存储在文本文件中。

如果有人能解释如何实现这个程序,我将非常感激

最佳答案

这本书是对的,管道可以用来保护关键部分,尽管如何做到这一点并不明显。

int *make_pipe_semaphore(int initial_count)
{
int *ptr = malloc(2 * sizeof(int));
if (pipe(ptr)) {
free(ptr);
return NULL;
}
while (initial_count--)
pipe_release(ptr);
return ptr;
}

void free_pipe_semaphore(int *sem)
{
close(sem[0]);
close(sem[1]);
free(sem);
}

void pipe_wait(int *sem)
{
char x;
read(sem[0], &x, 1);
}

void pipe_release(int *sem)
{
char x;
write(sem[1], &x, 1);
}

信号量中的最大可用资源因操作系统而异,但通常至少为 4096。这对于保护初始值和最大值均为 1 的关键部分来说并不重要。

用法:

/* Initialization section */
int *sem = make_pipe_semaphore(1);



/* critical worker */
{
pipe_wait(sem);
/* do work */

/* end critical section */
pipe_release(sem);
}

关于c - 将 UNIX 管道与 C 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3929365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com