使用下面的基本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/