• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 263
  • Last Modified:

POSIX Dead lock

Hey guys, im just trying to create 10 threads which then i want to print out in backwards order... so
"from thread 10", "from thread 9" ---> "from thread 1"

But im getting deadlocked after i get "from thread 10" to print.... Any ideas?

#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>

pthread_mutex_t mlock;
pthread_cond_t conditions[10];

int count = 10;


void * func(void * arg)
{
   int index = (int)arg - 1;

   pthread_mutex_lock(&mlock);

      while(count != (int)arg)
         pthread_cond_wait(&conditions[index], &mlock);

      printf("from thread %d\n", (int)arg);
      count--;
      index--;

      pthread_cond_signal(&conditions[index]);

    pthread_mutex_unlock(&mlock);

    return (NULL);
}


int main(int argc, char* argv[]) {
    int n,i;
    pthread_t threads[count];
    pthread_mutex_init(&mlock, NULL);

    for (i = 0; i < count; i++) {
      pthread_create(&threads[i], NULL, func, (void*)i+1);
      pthread_cond_init(&conditions[i], NULL);
    }

    for (i = 0; i < count; i++) {
      pthread_join(threads[i], NULL);
    }

    exit(1);
}
0
intazaar
Asked:
intazaar
1 Solution
 
efnCommented:
I don't know if this is the problem, but I can tell you one thing that looks fishy.

A thread might use a condition variable before it has been initialized.  Specifically, after a thread is started, it could easily get to the pthread_cond_wait call before the main thread has called pthread_cond_init.  This is not the order you want.

You could try moving the call to pthread_cond_init before the call to pthread_create and see if that helps.
0
 
intazaarAuthor Commented:
Thx mate, that was exactly it. Runs like a dream!
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now