c - ubuntu 上的 sem_init 使用 C 语言

标签 c linux pthreads posix semaphore

我正在编写一些使用 pthread 和信号量库的代码。这是我的代码,但它不起作用,我认为这是因为 sem_init 函数。我是 C 新手,真的不知道如何使用 sem_initsem_opensem_waitsem_post .有人可以给我一些建议吗??

#include <sys/mman.h>
#include <math.h>
#include <wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <unistd.h>
#include<fcntl.h>
sem_t sem1,sem2;

float Calculate(int a,int b)
{
    float d = ((a *a) + (b*b))/2;
    return d;
}

int main()
{
    int q;
    int i,j,x;
    float *Maddress, m, sum;

    Maddress=mmap(NULL,sizeof(float),PROT_READ|PROT_WRITE,MAP_SHARED,-1,0);

    sem_init(&sem2,0,1);
    sem_init(&sem1,0,0);
    sem_open("sem2",O_CREAT);
    sem_open("sem1",O_CREAT);


    if((q = sem_init(&sem1,1,0))!=0)
        printf("error in create\n");

    for(i=1;i<=10;i++)
    {
        j=fork();
        if(j==0)
        {

            printf("The child %d is executing\n",i);
            m=Calculate(i-1,i);
            printf("child %d calculated value: %f\n",i,m);
            sem_wait(&sem2);
            Maddress=&m;
            sem_post(&sem1);
            exit(EXIT_SUCCESS);
        }
    }           
    for(j=1;j<=10;j++)
    {
        wait(&x);
        if(WIFEXITED(x))
        {
            sem_wait(&sem1);
            sum=sum+ (*Maddress);
            sem_post(&sem2);


        }
    }
    printf("The final result is: %f \n",sum);

    sem_close(&sem1);
    sem_close(&sem2);
    return 0;
}

最佳答案

你应该像这样定义你的信号量:

sem_t sem1, sem2;

sem_init()而言,根据man 3 sem_init,原型(prototype)为:

int sem_init(sem_t *sem, int pshared, unsigned int value);

所以你必须像这样传递信号量:

sem_init(&sem1, 0, 0);

或者您需要的任何初始值。

同样适用于 sem_wait()sem_post()

关于c - ubuntu 上的 sem_init 使用 C 语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23019004/

相关文章:

linux - ExecShellResult 不喜欢我的管道

linux - 读取文件的方法

c - 当一个线程失败时退出所有线程

c - 将 argv[1] 作为参数传递给 pthread_create。

c - insmod:错误:无法插入模块 kprobe_example.ko:不允许操作

c - 如何修改makefile以便我可以在ARM平台上运行代码?

c - 栈内存是在运行时分配的还是编译时分配的?

linux - 在没有互联网的情况下安装软件包 Red Hat

c - 矩阵乘法:为什么非阻塞优于阻塞?

使用 pthreads 创建 makefile