Adrian
Adrian

Reputation: 20068

problem with posix threads c++

If i have 2 threads Thread1 and Thread2, but Thread2 will use some data that are procesed when Thread1 finishes.Is there a way for Thread2 to wait for Thread1 to finish and then get the data ?

Upvotes: 1

Views: 255

Answers (4)

SVGreg
SVGreg

Reputation: 2368

One way is to use condition vars: Ex:

pthread_mutex_t mx; 
pthead_cond_t cond; 

void first_f(void *) { 
...
    pthread_mutex_lock(&mx) 

// do something in first function
// the second function is waiting

    pthread_cond_signal(&cond); 
    pthread_mutex_unlock(&mx); 
  } 
  return NULL; 
} 

void second_f(void *) { 
...
    pthread_mutex_lock(&mx)    
    pthread_cond_wait(&cond, &mx); 

// waiting for first function until we catch a signal

    pthread_mutex_unlock(&mx); 
  } 
  return NULL; 
} 

The second way is to use two semaphores. First sem sets to 1, second set to zero. When the first function finishes, it sets first sem to 0, and second sem to 1. The second function waits until second semaphore is setted to 1 by first function and works.

Upvotes: 1

BMitch
BMitch

Reputation: 263637

If you need the data from thread1 and not just simple locking to prevent concurrent access, then you should use a semaphore:

   #include <semaphore.h>

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

   int sem_post(sem_t *sem);

   int sem_wait(sem_t *sem);

   int sem_trywait(sem_t *sem);

   int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);

   int sem_destroy(sem_t *sem);

The main program runs sem_init before launching the threads. Thread 1 runs a sem_post to indicate it's done. Thread 2 uses a sem_wait to ensure Thread 1 is finished before it starts.

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122391

Yes, you can use a mutex to 'guard' the data in question:

int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *abs_timeout);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

Upvotes: 0

bjornars
bjornars

Reputation: 1516

It is called a mutex. pthreads calls the pthread_mutex, you should find them in the docs.

Upvotes: 0

Related Questions