shijinghui1993 2015-07-04 02:06 采纳率: 0%
浏览 1677

Ubuntu下用信号量模拟的十字路口,可以在qt中实现吗,求大神解决以下是代码

sn.c南北方向
#include

#include
#include

#include
#include

#include
#include
#include

int sem_id;
void init(){
key_t key;int ret;
unsigned short sem_array[2];
union semun
{
int val;
struct semid_ds *buf;
unsigned short *array;
}arg;
key=ftok(".",'s');
sem_id=semget(key,2,IPC_CREAT|0644);
sem_array[0]=1;
sem_array[1]=0;

arg.array = sem_array;
ret = semctl(sem_id, 0, SETALL, arg);

if (ret == -1)
printf("SETALL failed (%d)\n", errno);

}
void del()
{
semctl(sem_id,IPC_RMID,0);
}
int car_num()
{
int ret;
srand(time(NULL));
ret=rand()%20;
return ret;
}
int main(int argc,char *argv[])
{
init();

struct sembuf sops[2];
sops[0].sem_num = 0;

sops[0].sem_op = -1;
sops[0].sem_flg = SEM_UNDO;

sops[1].sem_num = 1;

sops[1].sem_op = 1;

sops[1].sem_flg =SEM_UNDO;
printf("this is south north\n");
int remaining=0;
while(1)
{
int carnum=car_num();
carnum+=remaining;
printf("car num is %d\n",carnum);

    semop(sem_id,(struct sembuf *)&sops[0],1);  
    printf("now south north running......\n");

            int n=30;
            remaining=carnum;
            for(remaining;n>0;remaining--)
            {
              sleep(1);
              n-=3;
            }
    semop(sem_id,(struct sembuf *)&sops[1],1);  
    printf("run after \n");

            if(remaining<0)
                {
                    remaining=0;
                }
            printf("car num is %d\n",remaining);
    sleep(15);
}
del();

}
we.c东西方向
#include

#include
#include

#include
#include

#include
#include

int sem_id;
int car_num()
{
int ret;
srand(time(NULL));
ret=rand()%20;
return ret;
}

void init(){
key_t key;int ret;
key=ftok(".",'s');
sem_id=semget(key,2,IPC_CREAT|0644);
}
int main(int argc,char *argv[])
{
init();
int remaining;
struct sembuf sops[2];
sops[0].sem_num = 0;

sops[0].sem_op = 1;
sops[0].sem_flg = SEM_UNDO;

sops[1].sem_num = 1;

sops[1].sem_op = -1;

sops[1].sem_flg =SEM_UNDO;

printf("this is west east\n");
while(1)
{
int carnum=car_num();

    carnum+=remaining;
    printf("car num is %d\n",carnum);


    semop(sem_id,(struct sembuf *)&sops[1],1);  
    printf("now east west  running......\n");

    int n=30;
    remaining=carnum;
    for(remaining;n>0;remaining--)
           {
                sleep(1);
                n-=3;
           }

    semop(sem_id,(struct sembuf *)&sops[0],1);  
    printf("run after\n");

    if(remaining<0)
        {
              remaining=0;
        }
    printf("car num is %d\n",remaining);
    sleep(15);
}

}

  • 写回答

2条回答 默认 最新

  • devmiao 2015-07-19 15:44
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作