pthread_cond_t

0

Witam,
Czytam sobie o programowaniu wielowątkowym i jestem tym wszystkim odrobinę zdezorientowany ;-)

#include <stdio.h>
#include <pthread.h>
#include <stdbool.h>
#include <string.h>

char buf[32];
pthread_cond_t cond;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
bool isGreetingsMsgSet = false;


void* threadf1(void *arg)
{
    const char *msg = (const char*) arg;
    printf("%s\n", msg);

    pthread_mutex_lock(&mutex);
    strcpy(buf, "Hello world");
    isGreetingsMsgSet = true;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

void* threadf2(void *arg)
{
    const char *msg = (const char*) arg;
    printf("%s\n", msg);
    pthread_mutex_lock(&mutex);
    while (false == isGreetingsMsgSet)
    {
        pthread_cond_wait(&cond, &mutex);
    }
    printf("%s\n", buf);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
    pthread_t t1, t2;
    const char *msg1 = "Thread 1", *msg2 = "Thread 2";
    pthread_create(&t1, NULL, threadf1, (void*)msg1);
    pthread_create(&t2, NULL, threadf2, (void*)msg2);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    return 0;
}
 

mam taki prosty przykład jak powyżej czyli w skrócie 2 wątki wyświetlają napisy thread 1 i thread 2 ale dodatkowo musi najpierw nastąpić przypisanie do buf nim zawartość tej zmiennej zostanie wyświetlona (przypisanie w jednym wątku, wyświetlenie w drugim) pomijam już inne niuanse jak to że dostęp do stdout również powinien być w "sekcji krytycznej".

http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html

The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result.

czyli nim wywołam pthread_cond_wait(...) muszę "zablokować" mutex w tym wątku w którym wywołuję pthread_cond_wait tak? Dodatkowe pytanie, czy w funkcji threadf2 po:

pthread_mutex_lock(&mutex);
    while (false == isGreetingsMsgSet)
    {
        pthread_cond_wait(&cond, &mutex);
    }

mam ponownie wywoływać pthread_mutex_lock?

0

czyli nim wywołam pthread_cond_wait(...) muszę "zablokować" mutex w tym wątku w którym wywołuję pthread_cond_wait tak?

Wychodzi na to, że tak:

https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

1 użytkowników online, w tym zalogowanych: 0, gości: 1