Ejemplo n.º 1
0
void kind(int pos)
{
    enum STATUS state = HERANFAHREN;

    while (1)
    {
        /* Wagen steht an der Kreuzung */
        state = WARTEN;
        p(semid, pos);
        printf("Auto %d steht an der Kreuzung.\n", pos);

        /* Vergewissern, ob Strasse frei */
        do
        {
            sleep(3);
            printf("Auto %d wartet auf freie Fahrt.\n", pos);

            /* evtl Deadlock Entsperrung */
            if (get_sem(semid, ANZAHL_AUTOS+1) == pos)
                break;
        }
        while (get_sem(semid, (pos+1)%4) == 0 || get_sem(semid, ANZAHL_AUTOS) == 0);

        /* claimen der entsprechenden Strassenabschnitte */
        p(semid, ANZAHL_AUTOS);

        /* Ueberqueren der Strasse */
        state = FAHREN;
        printf("Auto %d ueberquert die Strasse.\n", pos);
        sleep(1);

        /* Zuruecksetzen der Deadlock Sperre, falls noetig */
        if (get_sem(semid, ANZAHL_AUTOS+1) == pos)
            set_sem(semid, ANZAHL_AUTOS+1, ANZAHL_AUTOS);

        /* Freigabe der entsprechenden Strassenabschnitte */
        v(semid, pos);
        v(semid, ANZAHL_AUTOS);
        printf("Auto %d hat die Strasse ueberquert.\n", pos);

        /* Zurueckkehren zur Kreuzung */
        state = HERANFAHREN;
        printf("Auto %d kehrt zur Kreuzung zurueck.\n", pos);
        sleep(3);
    }
}
Ejemplo n.º 2
0
int deadlock_observer()
{
    int i;

    /* warten alle Autos? */
    for (i=0; i<ANZAHL_AUTOS; ++i)
    {
        if (get_sem(semid, i))
            return 0;
    }

    /* ist kein Auto auf der Kreuzung? */
    if (!get_sem(semid, ANZAHL_AUTOS))
        return 0;

    return 1;
}
Ejemplo n.º 3
0
int main(int argc, char **argv) {
	shmid = shmget( IPC_PRIVATE, sizeof( varijable ) * 100, 0600 );
	if( shmid == -1 ){
		printf( "Greska prilikom stvaranja zajednicke memorije\n" );
		exit(1);	
	}

	zajednicke = ( varijable * ) shmat( shmid, NULL, 0 );
	
	get_sem( 5, & (zajednicke->semid) );
	// postavljanje semafora
	set_sem( 5, semPUN, zajednicke->semid );
	set_sem( 0, semPRAZAN, zajednicke->semid );
	set_sem( 1, semPISI, zajednicke->semid );
	set_sem( 0, semGO1, zajednicke->semid );
	set_sem( 0, semGO2, zajednicke->semid );

	sigset( SIGINT, clean_exit );
	
	switch( fork() ){
		case -1:
			printf( "Greska prilikom stvaranja procesa!\n" );
			break;
		case 0:
			proizvodac( 0 );
			exit( 0 );
			break;
	}

	switch( fork() ){
		case -1:
			printf( "Greska prilikom stvaranja procesa!\n" );
			break;
		case 0:
			proizvodac( 1 );
			exit( 0 );
			break;
	}

	switch( fork() ){
		case -1:
			printf( "Greska prilikom stvaranja procesa!\n" );
			break;
		case 0:
			potrosac();
			exit( 0 );
			break;
	}
	

	wait( NULL );	wait( NULL );	wait( NULL );

	clean_exit( 0 );
	return 0;
}
Ejemplo n.º 4
0
void
m_destroy(void)
{
	int rta;
	sem_t * sem;
	sem = get_sem();
	printf("A ejecutar: sem_destroy(%p);\n", sem);
	rta = sem_destroy(sem);
	if ( rta == -1 )
		printf("Error al hacer destroy, errno = %d (%s)\n", errno, strerror(errno));
	
	putchar('\n');
}
Ejemplo n.º 5
0
static int unlock(void)
{
	int unlocked = 0;
	if(bandwidth_semaphore == -1)
	{
		get_sem(&bandwidth_semaphore, (key_t)(BANDWIDTH_SEMAPHORE_KEY) );
	}
	if(bandwidth_semaphore != -1)
	{
		unlocked = unlock_sem(bandwidth_semaphore);
	}
	return unlocked;
	
}
Ejemplo n.º 6
0
static int baytrail_i2c_acquire(struct dw_i2c_dev *dev)
{
    u32 sem = PUNIT_SEMAPHORE_ACQUIRE;
    int ret;
    unsigned long start, end;

    might_sleep();

    if (!dev || !dev->dev)
        return -ENODEV;

    if (!dev->release_lock)
        return 0;

    /* host driver writes to side band semaphore register */
    ret = iosf_mbi_write(BT_MBI_UNIT_PMC, MBI_REG_WRITE, PUNIT_SEMAPHORE, sem);
    if (ret) {
        dev_err(dev->dev, "iosf punit semaphore request failed\n");
        return ret;
    }

    /* host driver waits for bit 0 to be set in semaphore register */
    start = jiffies;
    end = start + msecs_to_jiffies(SEMAPHORE_TIMEOUT);
    do {
        ret = get_sem(dev->dev, &sem);
        if (!ret && sem) {
            acquired = jiffies;
            dev_dbg(dev->dev, "punit semaphore acquired after %ums\n",
                    jiffies_to_msecs(jiffies - start));
            return 0;
        }

        usleep_range(1000, 2000);
    } while (time_before(jiffies, end));

    dev_err(dev->dev, "punit semaphore timed out, resetting\n");
    reset_semaphore(dev->dev);

    ret = iosf_mbi_read(BT_MBI_UNIT_PMC, MBI_REG_READ, PUNIT_SEMAPHORE, &sem);
    if (ret)
        dev_err(dev->dev, "iosf failed to read punit semaphore\n");
    else
        dev_err(dev->dev, "PUNIT SEM: %d\n", sem);

    WARN_ON(1);

    return -ETIMEDOUT;
}
Ejemplo n.º 7
0
void
m_getvalue(void)
{
	int rta, value;
	sem_t * sem;
	sem = get_sem();
	printf("A ejecutar: get_value(%p);\n", sem);
	rta = sem_getvalue(sem, &value);
	if ( rta == -1 )
		printf("Error al hacer trywait, errno = %d (%s)\n", errno, strerror(errno));
	else
		printf("Getvalue devolvio %d\n", value);

	putchar('\n');
}
Ejemplo n.º 8
0
static int		lemipc_bsc(int no_team, char *path)
{
  t_lemipc		lemipc;

  if (no_team < 1 || no_team > 255)
    return (lemipc_error(NO_TEAM_ERROR));
  if ((lemipc.key = ftok(path, 0)) == -1)
    return (lemipc_perror(FTOK_ERROR));
  lemipc.no_team = no_team;
  lemipc.pos = -1;
  lemipc.killed_by = 0;
  lemipc.is_alone = TRUE;
  lemipc.is_dead = FALSE;
  if (get_shm(&lemipc) == EXIT_FAILURE ||
      get_sem(&lemipc) == EXIT_FAILURE ||
      get_msgq(&lemipc) == EXIT_FAILURE ||
      launch_player(&lemipc) == EXIT_FAILURE)
    return (EXIT_FAILURE);
  return (EXIT_SUCCESS);
}
Ejemplo n.º 9
0
void* broadcasting_agent(void *arg) {
    int bsem_id;
    key_t bsem_key = ftok(FTOK_PATH, BSEM_ID);
    /* Get the id of the blackboard Semaphore */
    bsem_id = get_sem(bsem_key);

    int bshm_id;
    key_t bshm_key = ftok(FTOK_PATH, BSHM_ID);
    /* Get the id of the blackboard shared memory segment */
    bshm_id = get_blackboard(bshm_key);
    char *blackboard;

    /* Attach to the shared memory */
    blackboard = blackboard_attach(bshm_id);

    log_info("broadcasting agent: waiting for trigger");
    pthread_mutex_lock(&trigger_mutex);
    while(1) {
        /* Wait for the trigger */
        pthread_cond_wait(&trigger_bcast, &trigger_mutex);
        switch (broadcast_type) {
            case STATUS:
                log_debug("broadcasting agent: received status trigger");
                broadcast_status();
                break;
            case BLACKBOARD:
                log_debug("broadcasting agent: received blackboard trigger");
                broadcast_blackboard(blackboard, bsem_id, 1);
                break;
            case CLEAR:
                log_debug("broadcasting agent: received clear trigger");
                broadcast_blackboard(blackboard, bsem_id, 0);
                break;
        }
    }
    pthread_mutex_unlock(&trigger_mutex);
    /* Detach from the shared memory */
    blackboard_detach(blackboard);

    pthread_exit(NULL);
}
Ejemplo n.º 10
0
int main(int argc, char *argv[]) {
	
	pid_t pid, wpid;
	int status = 0;
	tpBuffer pBuffer;
	int semId; // Identificador del semáforo

	int i, id_proc;
	int np = 0; // Número de procesos a crear.
	int times; // Número de elementos que procesará cada proceso.

	get_args(argc, argv, &np, &times);
	
	sprintf(mensaje, "[padre (pid = %d)] BEGIN \n", getpid());
	write (STDOUT_FILENO, mensaje, strlen(mensaje));

	for (i=0; i<np; i++){
		if ((pid = fork()) == 0){ // hijo
			id_proc = i;
			sprintf(mensaje, "[hijo (pid = %d)]\t EMPIEZA\n", getpid());
			write (STDOUT_FILENO, mensaje, strlen(mensaje));

			pBuffer = get_buf();
			semId = get_sem();
			
			consume (id_proc, times, pBuffer, semId);

			leave_buff(pBuffer);
			sprintf(mensaje, "[hijo (pid = %d)]\t ACABA\n", getpid());
			write (STDOUT_FILENO, mensaje, strlen(mensaje));
			return 1;
		}
	}
	
	while ((wpid = wait(&status)) > 0);
	sprintf(mensaje, "[padre (pid = %d)] Sale de la espera\n", getpid());
	write (STDOUT_FILENO, mensaje, strlen(mensaje));
	

	return 0;
}
Ejemplo n.º 11
0
static int lock(unsigned long max_wait_milliseconds)
{
	int locked = 0;
	if(bandwidth_semaphore == -1)
	{
		get_sem(&bandwidth_semaphore, (key_t)(BANDWIDTH_SEMAPHORE_KEY) );
	}
	if(bandwidth_semaphore != -1)
	{
		do
		{
			locked = lock_sem(bandwidth_semaphore);
			if(locked == 0 && max_wait_milliseconds > 25)
			{
				usleep(1000*25);
			}
			max_wait_milliseconds = max_wait_milliseconds > 25 ? max_wait_milliseconds - 25 : 0;
		} while(locked == 0 && max_wait_milliseconds > 0);
	}
	return locked;
}
Ejemplo n.º 12
0
int main(int argc, char **argv) {

	int num_items = 15;

	if((argc == 3 && (strcmp("-items", argv[1]) == 0))){
		int aux = atoi(argv[2]);
		if(aux < MAX_ITEMS && aux > 0)
			num_items = aux;
		else{
			sprintf(mensaje, "Error: el número de items debe estar comprendido entre 0 y %d\n", MAX_ITEMS);
			write (STDOUT_FILENO, mensaje, strlen(mensaje));

			exit(0);
		}
	} else if (argc != 1) {
		sprintf(mensaje, "Usage: inicializa [-items] [num_items]\n");
		write (STDOUT_FILENO, mensaje, strlen(mensaje));

		exit(0);
	}

	tpBuffer pBuffer = get_buf(); // Se crea el área de memoria compartida
	sprintf(mensaje, "[padre (pid = %d)] Buffer creado!\n", getpid());
	write (STDOUT_FILENO, mensaje, strlen(mensaje));
	
	initialize(pBuffer, num_items); // Se inicializa

	int semId = get_sem(); // Se crean los semáforos
	set_sem_value (semId, SEM_VACIO, num_items);
	set_sem_value (semId, SEM_MUTEX, 1);
	set_sem_value (semId, SEM_LLENO, 0);

	sprintf(mensaje, "[padre (pid = %d)] Semáforo creado!\n", getpid());
	write (STDOUT_FILENO, mensaje, strlen(mensaje));
	return 0;
}
Ejemplo n.º 13
0
static int baytrail_i2c_acquire(struct dw_i2c_dev *dev)
{
	u32 addr;
	u32 sem = PUNIT_SEMAPHORE_ACQUIRE;
	int ret;
	unsigned long start, end;

	might_sleep();

	if (!dev || !dev->dev)
		return -ENODEV;

	if (!dev->release_lock)
		return 0;

	iosf_mbi_punit_acquire();
	iosf_mbi_call_pmic_bus_access_notifier_chain(MBI_PMIC_BUS_ACCESS_BEGIN,
						     NULL);

	/*
	 * Disallow the CPU to enter C6 or C7 state, entering these states
	 * requires the punit to talk to the pmic and if this happens while
	 * we're holding the semaphore, the SoC hangs.
	 */
	pm_qos_update_request(&dev->pm_qos, 0);

	addr = get_sem_addr(dev);

	/* host driver writes to side band semaphore register */
	ret = iosf_mbi_write(BT_MBI_UNIT_PMC, MBI_REG_WRITE, addr, sem);
	if (ret) {
		dev_err(dev->dev, "iosf punit semaphore request failed\n");
		goto out;
	}

	/* host driver waits for bit 0 to be set in semaphore register */
	start = jiffies;
	end = start + msecs_to_jiffies(SEMAPHORE_TIMEOUT);
	do {
		ret = get_sem(dev, &sem);
		if (!ret && sem) {
			acquired = jiffies;
			dev_dbg(dev->dev, "punit semaphore acquired after %ums\n",
				jiffies_to_msecs(jiffies - start));
			return 0;
		}

		usleep_range(1000, 2000);
	} while (time_before(jiffies, end));

	dev_err(dev->dev, "punit semaphore timed out, resetting\n");
out:
	reset_semaphore(dev);

	ret = iosf_mbi_read(BT_MBI_UNIT_PMC, MBI_REG_READ, addr, &sem);
	if (ret)
		dev_err(dev->dev, "iosf failed to read punit semaphore\n");
	else
		dev_err(dev->dev, "PUNIT SEM: %d\n", sem);

	WARN_ON(1);

	return -ETIMEDOUT;
}
Ejemplo n.º 14
0
int main(int argc, char* argv[])
{
	int r = 0, semid;

	parse_args(argc, argv);

	if (argc - optind != 1) {
		print_usage();
		exit(EXIT_FAILURE);
	}

	if (use_id && create == 1) {
		fprintf(stderr, "** incompatible options used: -c and -i\n");
		exit(EXIT_FAILURE);
	}

	if (create == 1) {
		semid = create_sem(argv[optind], nbmembers);
		if (semid == -1)
			r = semid;
	} else {
		if (use_id) {
			semid = atoi(argv[optind]);
		} else {
			semid = get_sem(argv[optind]);
		}

		if (create == -1) { /* user wants to remove the SEM object */
			int r;
			r = delete_sem(semid);
			if (r)
				exit(EXIT_FAILURE);

			exit(EXIT_SUCCESS);
		}
	}

	if (semid == -1)
		exit(EXIT_FAILURE);

	switch (todo) {
	case ADD:
		r = add_to_member(semid, member, blocking, undo, delta);
		break;
	case SHOW:
		r = display_sem(semid);
		break;
	case TESTLOOP:
		r = test_loop(semid, undo);
		break;
	case NOTHING:
		if (create == 0) {
			print_usage();
			r = -1;
		}
		break;
	}

	if (r)
		exit(EXIT_FAILURE);

	exit(EXIT_SUCCESS);
}
Ejemplo n.º 15
0
int MySemaphoreDestroy(MySemaphore sem)
{

	if(sem==NULL)
	{
		//printf(" MySemaphoreDestroy : sem is NULL....returning... \n");
		return 0;
	}

	struct sema *passed_sem=(struct sema *)sem;
	struct sema *c_sem=get_sem(passed_sem);
	
	//printf(" MySemaphoreDestroy : enter for sem=%d and fetched sem=%d.... \n",passed_sem->sid,c_sem->sid);
	
	//Do not destroy semaphore if any threads are blocked on the queue. Return 0 on success, -1 on failure.
	if(c_sem->sb_front!=NULL)
	{
		//printf("MySemaphoreDestroy: this sem's sblocked queue is not empty.... So not destroying... \n");
		return -1;
	}


	//Now delete the sem, from Semaphore list...
	
	struct sema *stmp=NULL;
	struct sema *sprev=NULL;

	//only one sem, and that's to be deleted...	
	if(sfront==srear && sfront->sid==c_sem->sid)
	{
		stmp=sfront;
		sfront=NULL;
		srear=NULL;
		free(stmp);
	} else if(sfront->sid==c_sem->sid)
	{ // more than one sem, but first one to be deleted...
		stmp=sfront;
		sfront=sfront->other;
		free(stmp);
	} else 
	{ // Not first sem match, need to traverse through list....
		stmp=sfront;
		
		while(stmp!=NULL && stmp->sid!=c_sem->sid)
		{
			sprev=stmp;
			stmp=stmp->other;
		}
		
		if(stmp!=NULL && stmp->sid==c_sem->sid)
		{
			sprev->other=stmp->other;
			free(stmp);
		} else if(stmp==NULL)
		{
			//printf("MySemaphoreDestroy: sem= %d does not exist... \n",c_sem->sid);
		}
	}
	
	//printf(" MySemaphoreDestroy : EXIT .... \n");
	
	return 0;
	
}
Ejemplo n.º 16
0
void MySemaphoreSignal(MySemaphore sem)
{
   struct sema *passed_sem=(struct sema *)sem;
	struct sema *c_sem=get_sem(passed_sem);

	if(c_sem==NULL)
	{
		//printf("MySemaphoreSignal : sem is NULL.... returning.... \n");
		return;
	}
	
	//printf("MySemaphoreSignal : Enter... for sem=%d \n",c_sem->sid);
	
	if(c_sem->val>0)
	{
		//printf("MySemaphoreSignal : sem=%d is >0... simply incrementing...new val=%d \n",c_sem->sid,(c_sem->val+1));
		c_sem->val = (c_sem->val)+1;
	}
	else if(c_sem->val==0)
	{
		//if sb_thread queue empty, no thread is waiting...than increase semaphore...
		if(c_sem->sb_front==NULL)
		{
			c_sem->val=(c_sem->val)+1;
		}
		else
		{
			int sbth_id=-2;
		
			//pop the sb_thread queue, and get the first entered sb_thread id
			struct sb_thread *sb_tmp=c_sem->sb_front;
			
			if(c_sem->sb_front==c_sem->sb_rear)
			{
				c_sem->sb_front=NULL;
				c_sem->sb_rear=NULL;
			}
			else 
			{
				c_sem->sb_front=c_sem->sb_front->sb_next;
				
			}
			
			sbth_id=sb_tmp->sb_id;
		
			// No need to, make semaphore =1 now, untill first ready thread get access to it...
			//Time to shift first blocked thread into ready queue...look from MyThreadExit

			// First, get thread via thread id from blocked queue...
			struct node *sblocked_th=bgetNode(sbth_id);
			
			//second, insert thread into RQ...
			//printf(" MySemaphoreSignal : thread: %d , inserting into ready queue \n",sblocked_th->tid);
			struct node *sblocked_to_ready=insert_q(sblocked_th->cnxt,sblocked_th->tid,sblocked_th->pid,sblocked_th->join_th,sblocked_th->join_th_rear);
			//printf(" MySemaphoreSignal: Thread = %d moved to ready Queue \n ",sblocked_to_ready->tid);
			
			//Third, remove thread id from BQ...
			bremoveNode(sblocked_th->tid);
			//printf(" MySemaphoreSignal: Thread = %d removed from blocked Queue \n",sblocked_to_ready->tid);

			//printf(" MySemaphoreSignal: Moved thread= %d from blocked to ready queue...continuing current thread=%d \n",sbth_id,curr_th->tid);

		}	
	}
	
	//printf(" MySemaphoreSignal: EXIT ... \n");
}
Ejemplo n.º 17
0
void MySemaphoreWait(MySemaphore sem)
{
   struct sema *passed_sem=(struct sema *)sem;
	struct sema *c_sem=get_sem(passed_sem);
	
	if(c_sem==NULL)
	{
		//printf("MySemaphoreWait : sem is NULL.... returning.... \n");
		return;
	}
	
	//printf("MySemaphoreWait : Enter... for sem=%d \n",c_sem->sid);
	
	if(c_sem->val>0)
	{
		//printf("MySemaphoreWait : resource available for c_sem=%d ...simply decrementing its value , now val=%d\n",c_sem->sid,(c_sem->val-1));
		c_sem->val = (c_sem->val)-1;
	}
	else if(c_sem->val==0)
	{
		//printf(" MySemaphoreWait : c_sem->val is already 0.... add this thread into sem's sblocked list...and then....Move current thread=%d to blocked queue... \n",curr_th->tid);
		// need to add curr_th into, this semaphore's FIFO blocked thread id list....

		struct sb_thread *tmp=(struct sb_thread *)malloc(sizeof(struct sb_thread));
		
		if(tmp==NULL)
		{
			//printf(" MySemaphoreWait : Memory not allocated...max limit reached for threads....returning gracefully...\n");
			swapcontext(&dmy_cnxt,&init_cnxt);
		}
		
		tmp->sb_id=curr_th->tid;
		tmp->sb_next=NULL;

		//printf("MySemaphoreWait : init tmp...\n");
		if(c_sem->sb_front == NULL)
		{
			c_sem->sb_front=tmp;
			c_sem->sb_rear=tmp;
		} else
		{
			c_sem->sb_rear->sb_next=tmp;
			c_sem->sb_rear=tmp;
		}

		// Move current thread to blocked queue, run first ready queue, lookup MyThreadJoin for reference....
		// POP first ready thread...

	
		// todo: code to move current thread to blocked queue...
	
		struct node * blocked_th=binsert_q(curr_th->cnxt,curr_th->tid,curr_th->pid,curr_th->join_th,curr_th->join_th_rear);
	
		//printf("MySemaphoreWait : current thread:%d entered in BQ , but actual current thread is= %d\n",blocked_th->tid, curr_th->tid);

		//saving current thread pointers for future failure recovery	
		int old_th=curr_th->tid;
		int old_pr=curr_th->pid;
		ucontext_t old_cnxt=curr_th->cnxt;
		struct join_list *old_jfront=curr_th->join_th;
		struct join_list *old_jrear=curr_th->join_th_rear;

		//printf("MySemaphoreWait : popping first RQ thread...\n");
		ucontext_t new_cnxt;
		struct node * new_th=pop_q();
		
		if(new_th == NULL)
		{
			//printf(" MySemaphoreWait: ready queue empty ... \n");
			swapcontext(&dmy_cnxt,&init_cnxt);
		}
	
		new_cnxt=new_th->cnxt;
		//updating current thread pointers
		curr_th->tid=new_th->tid;
		curr_th->pid=new_th->pid;
		curr_th->cnxt=new_th->cnxt;
		curr_th->join_th=new_th->join_th;
		curr_th->join_th_rear=new_th->join_th_rear;
	
		//printf("MySemaphoreWait: swap context from thread : %d  to first ready thread : %d ... \n",old_th,curr_th->tid);
	
		if(swapcontext(&(blocked_th->cnxt),&new_cnxt)==-1)
		{
			//printf("MySemaphoreWait: Blocking swapcontext error... \n");
			curr_th->tid=old_th;
			curr_th->pid=old_pr;
			curr_th->cnxt=old_cnxt;
			curr_th->join_th=old_jfront;
			curr_th->join_th_rear=old_jrear;
			bremoveNode(curr_th->tid);
			//printf("MySemaphoreWait: Blocking swapcontext error recovery done...\n");
		}
	
		// After resuming from ready - queue,
		//printf(" MySemaphoreWait: Semaphore wait over, for current thread= %d ....\n",curr_th->tid);
		
	}
	//printf(" MySemaphoreWait : EXIT .... \n");
}