user121986
user121986

Reputation: 91

Best mechanism for event based communication in C(linux platform)

I want to communicate between the two threads. there is only one event that triggers other thread.

My condition would be that event based communication should be efficient. i tried using the message queue but usually mq_send takes time.

Upvotes: 0

Views: 727

Answers (1)

Idan
Idan

Reputation: 165

I think that your best way is to use Pthread_mutex and pthread_cond

You should wait for event as follow:

    pthread_mutex_t lock;
    pthread_cond_t cond;



    pthread_mutex_lock(&>lock);
    /* releasing the mutex and block untill a cond get a signal*/
    pthread_cond_wait(&cond, &lock);
    /* execute your code */

    your_condtion = 0;

    /* signaling the producer that we "consumed" the data */
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);

You shoud send event as follow:

    /* checking if consumer already used our data */
    pthread_mutex_lock(&lock);
    while(your_condition != 0)
        pthread_cond_wait(&cond, &lock);
    /* execute your code */
            your_condition = 1;
    /* sending event */
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);

You can use my producer consumer example as reference

Upvotes: 1

Related Questions