1

I'm building a multithread applications. My threads have to execute an instruction block only if a pointer becomes !=nil

void *fun(struct coordinates *app){

struct coordinates coord;
coord.x = app->x;
coord.y = app->y;
//printf("\n %p %d %d", t_queue[coord.x][coord.y], coord.x, coord.y);

while(1){
    if(t_queue[coord.x][coord.y]){
        pthread_mutex_lock(&Thread_Mutex);

            /*
                critical zone
            */


        pthread_mutex_unlock(&Thread_Mutex);
    }
    //sleep(1);
}

pthread_exit(nil);
}

Instead of the if (t_queue[coord.x][coord.y]), I'd like to use another function that really waits and does not use so much cpu (else my cpu go to 100%, only using sleep it will go down to 10% only checking if the variable become != to nil)

roschach
  • 8,390
  • 14
  • 74
  • 124
osharko
  • 204
  • 3
  • 19
  • It seems that you need [condition variables](https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables). – Iharob Al Asimi May 24 '15 at 15:28
  • yes, but i can't find nothing that explain me how use it. i tried with this code pthread_cond_wait(&Condition_Mutex, t_queue[coord.x][coord.y]); but i recived segmentation fault – osharko May 24 '15 at 15:30
  • A condition goes along with a mutex, protecting it. Btw: Learning to code by just "*trying*" is harder then the hard way. – alk May 24 '15 at 15:31
  • this is what i haven't understand.. could you explain it to me? – osharko May 24 '15 at 15:32
  • See the link posted by *iharob* and just scroll down a bit to find a nice example. Also it might make sense to read the rest aorund this example. – alk May 24 '15 at 15:35
  • i had not realized that it is a link. i will read it now – osharko May 24 '15 at 15:39
  • while(1){ pthread_mutex_lock(&Thread_Mutex); if(t_queue[coord.x][coord.y]){ pthread_cond_wait(&Condition_Mutex, &Thread_Mutex); /* critical zone */ } pthread_mutex_unlock(&Thread_Mutex); //sleep(1); } it's still wrong.. i'm not understanding the problem – osharko May 24 '15 at 15:50
  • The waiting pattern looks like this (pseudo-code): `lock(mutex); while (your test fails) wait(cond, mutex); unlock(mutex)` and the signaling pattern like this: `lock(mutex); set value to be tested; signal(cond); unlock(mutex)`. Read the tutorial carefully. You will find these patterns in there. Mainly this is all about protecting shared variables against concurrent/simultaneously access. – alk May 24 '15 at 16:01
  • @alk: The question linked as duplicate is not really the same question at all. [*Resume a program if variable's value changes*](https://stackoverflow.com/questions/22090545/resume-a-program-if-variables-value-changes/22091026#22091026) is much closer. – caf May 25 '15 at 00:43

0 Answers0