c - 将Pthread转换为进程fork()

标签 c multithreading pthreads fork posix

使用下面的基本pthread代码,将pthread_create转换为fork()并实现类似结果的方法是什么。

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h> 
#include <unistd.h>
sem_t mutex; 
void* wait_t(void* a)
{
    (int)a--;
    if ((int)a < 0)
    {
        sem_wait(&mutex);
        printf("waiting\n");
    }
}
void* signal_t(void* a)
{
    (int)a++;
    if ((int)a <= 0)
    {
        printf("signal\n");
        sem_post(&mutex);
    }
}
int main()
{
    sem_init(&mutex, 0, 1);
    int i = -2;
    pthread_t t1, t2; 
    pthread_create(&t1, NULL, wait_t, i);
    pthread_create(&t2, NULL, signal_t, i); 
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    exit(0); 
}

最佳答案

除非丢失了某些内容,否则以下代码使您可以使用进程而不是线程来实现相同的功能。

#include <stdio.h>
#include <semaphore.h> 
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

sem_t mutex; 
void wait_t(int a)
{
    a--;
    if (a < 0)
    {
        sem_wait(&mutex);
        printf("waiting\n");
    }
}

void signal_t(int a)
{
    a++;
    if (a <= 0)
    {
        printf("signal\n");
        sem_post(&mutex);
    }
}

int main()
{
    sem_init(&mutex, 0, 1);
    int i = -2;

    if(fork() == 0){ // create 1st child process
        wait_t(i);
        exit(0);
    }

    if(fork() == 0){ // create 2nd child process
        signal_t(i);
        exit(0);
    }


    wait(NULL);
    wait(NULL);

    exit(0); 
}

注意:建议您不要验证fork()引发的任何可能的错误。

关于c - 将Pthread转换为进程fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61575540/

相关文章:

c++ - 有没有办法将成员函数传递给 pthread_cleanup_push?

linux - 在 linux 中使用命令行检查单个线程优先级

c - 读取字符串 C - Linux

c - 使用二维数组调用函数时出现段错误

c - 为什么我不能编译我的 C 代码?

c++ - 在 cpp 中使用 pthread_mutex_t

c - c语言搜索算法执行时间(精度)

java - 进入同步块(synchronized block)是原子的吗?

c++ - OpenCV 多线程给出错误

java - 将锁转移到 Java 中的衍生线程