programing

pthread 조건 변수를 언제 사용해야 합니까?

lastcode 2023. 10. 29. 19:45
반응형

pthread 조건 변수를 언제 사용해야 합니까?

pthread 질문:

조건 변수는 다른 스레드가 pthread_cond_wait를 호출하기 전에 pthread_cond_wait를 호출하는 경우에만 작동하는 것으로 나타납니다.기다리기 전에 어떻게든 알림이 발생하면 대기가 중단됩니다.

제 질문은 조건 변수는 언제 사용해야 합니까?

스케줄러는 스레드를 선점할 수 있으며 대기 전에 알림이 발생할 수 있습니다.

세마포어에 대기하는 것은 이런 문제가 없습니다. 카운터가 있습니다.

조건부 변수가 세마포어보다 나은 경우는 언제입니까?

테스트 내용은 다음과 같습니다.

파일 condvar.c

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

// test of conditional variables;
// if cond-var is notified before wait starts, then wait never wakes up !!!
// better to use semaphores than this crap.

pthread_mutex_t cond_var_lock =  PTHREAD_MUTEX_INITIALIZER; 
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;

int wait_first = 1;

void *tfunc(void *arg)
{
    (void) arg;

    if (!wait_first)
        sleep(1);

    fprintf(stderr,"on enter cond_var_lock %lx\n", pthread_self());
    pthread_mutex_lock( &cond_var_lock);
    fprintf(stderr,"before pthread_cond_wait %lx\n", pthread_self());
    pthread_cond_wait( &cond_var, &cond_var_lock);
    fprintf(stderr,"after pthread_cond_wait %lx\n", pthread_self());
    pthread_mutex_unlock( &cond_var_lock);
    fprintf(stderr,"after exit cond_var_lock %lx\n", pthread_self());

    return 0;
}

int main(int argc, char *argv[])
{
    pthread_t th;

    if (argc > 0) 
    wait_first = atoi( argv[1] );

    if (wait_first)
    {
        fprintf(stderr,"********* Wait first ***********\n");
    } else {
        fprintf(stderr,"********* Notify first *********\n");
    }


    pthread_create( &th, 0, tfunc, 0 );

    if (wait_first)
    {
        sleep(1);
    } 

    fprintf(stderr, "! on enter cond_var_lock %lx\n", pthread_self());
    pthread_mutex_lock( &cond_var_lock);
    fprintf(stderr, "! before pthread_cond_signal %lx\n", pthread_self());
    pthread_cond_signal( &cond_var );
    fprintf(stderr, "! after pthread_cond_signal %lx\n", pthread_self());
    pthread_mutex_unlock( &cond_var_lock);
    fprintf(stderr, "! after exit cond_var_lock %lx\n", pthread_self());

    sleep(5);
    return 0;    
}

파일 test.sh

#!/bin/sh

set -e
set -x

gcc condvar.c -o condvar -lpthread

./condvar 1

./condvar 0

시험출력

Output:

+ gcc condvar.c -o condvar -lpthread
+ ./condvar 1
********* Wait first ***********
on enter cond_var_lock b7779b70
before pthread_cond_wait b7779b70
! on enter cond_var_lock b777a6c0
! before pthread_cond_signal b777a6c0
! after pthread_cond_signal b777a6c0
! after exit cond_var_lock b777a6c0
after pthread_cond_wait b7779b70
after exit cond_var_lock b7779b70
+ ./condvar 0
********* Notify first *********
! on enter cond_var_lock b785c6c0
! before pthread_cond_signal b785c6c0
! after pthread_cond_signal b785c6c0
! after exit cond_var_lock b785c6c0
on enter cond_var_lock b785bb70
before pthread_cond_wait b785bb70

조건 변수는 대기 장소로 사용하고 통지를 받아야 합니다.그것들은 조건 그 자체도 아니고 사건도 아닙니다.이 조건은 주변의 프로그래밍 로직에 포함됩니다.조건 변수의 일반적인 사용 패턴은 다음과 같습니다.

// safely examine the condition, prevent other threads from
// altering it
pthread_mutex_lock (&lock);
while ( SOME-CONDITION is false)
    pthread_cond_wait (&cond, &lock);

// Do whatever you need to do when condition becomes true
do_stuff();
pthread_mutex_unlock (&lock);

반면, 조건 변수를 나타내는 스레드는 일반적으로 다음과 같이 보입니다.

// ensure we have exclusive access to whathever comprises the condition
pthread_mutex_lock (&lock);

ALTER-CONDITION

// Wakeup at least one of the threads that are waiting on the condition (if any)
pthread_cond_signal (&cond);

// allow others to proceed
pthread_mutex_unlock (&lock)

언급URL : https://stackoverflow.com/questions/20772476/when-to-use-pthread-condition-variables

반응형