1. 程式人生 > >線程的條件變量實例

線程的條件變量實例

thread sig csdn jsb read water 時間 fill .net

情景1:

Jack開著一輛出租車來到一個網站停車。看見沒人就走了。過段時間。Susan來到網站準備乘車。可是沒有來,於是就等著。過了一會Mike開著車來到了這個網站,Sunsan就上了Mike的車走了。如圖所看到的:

技術分享

程序實現該情景:

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

pthread_cond_t taxicond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t taximutex = PTHREAD_MUTEX_INITIALIZER;

void *traveler_arrive(void *name)
{
    char *p = (char *)name;

    printf ("Travelr: %s need a taxi now!\n", p);
    pthread_mutex_lock(&taximutex);
    pthread_cond_wait(&taxicond, &taximutex);
    pthread_mutex_unlock(&taximutex);
    printf ("traveler: %s now got a taxi!\n", p);
    pthread_exit(NULL);
}

void *taxi_arrive(void *name)
{
    char *p = (char *)name;
    printf ("Taxi: %s arrives.\n", p);
    pthread_cond_signal(&taxicond);
    pthread_exit(NULL);
}

int main (int argc, char **argv)
{
    char *name;
    pthread_t thread;
    pthread_attr_t threadattr;
    pthread_attr_init(&threadattr);

    name = "Jack";
    pthread_create(&thread, &threadattr, taxi_arrive, name);
    sleep(1);
    name = "Susan";
    pthread_create(&thread, &threadattr, traveler_arrive, name);
    sleep(1);
    name = "Mike";
    pthread_create(&thread, &threadattr, taxi_arrive, name);
    sleep(1);

    return 0;
} /* ----- End of main() ----- */

情景2:

Jack開著一輛出租車來到一個網站停車,看見沒人就等著。過段時間,Susan來到網站準備乘車看見了Jack的出租車,於是就上去了。過了一會Mike開著車來到了這個網站,看見沒人救等著。

如圖所看到的:

技術分享

程序實現該情景:

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

int travelercount = 0;
pthread_cond_t taxicond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t taximutex = PTHREAD_MUTEX_INITIALIZER;

void *traveler_arrive(void *name)
{
    char *p = (char *)name;

    pthread_mutex_lock(&taximutex);

    printf ("traveler: %s need a taxi now!\n", p);
    travelercount++;
    pthread_cond_wait(&taxicond, &taximutex);
            
    pthread_mutex_unlock(&taximutex);
    printf ("traveler: %s now got a taxi!\n", p);
    pthread_exit(NULL);
}

void *taxi_arrive(void *name)
{
    char *p = (char *)name;
    printf ("Taxi: %s arrives.\n", p);
    for(;;){
        if(travelercount){
            pthread_cond_signal(&taxicond);
            travelercount--;
            break;
        }
    }

    pthread_exit(NULL);
}

int main (int argc, char **argv)
{
    char *name;
    pthread_t thread;
    pthread_attr_t threadattr;
    pthread_attr_init(&threadattr);

    name = "Jack";
    pthread_create(&thread, &threadattr, taxi_arrive, name);
    sleep(1);
    name = "Susan";
    pthread_create(&thread, &threadattr, traveler_arrive, name);
    sleep(3);
    name = "Mike";
    pthread_create(&thread, &threadattr, taxi_arrive, name);
    sleep(4);

    return 0;
} /* ----- End of main() ----- */

author: fulinux

E-mail: [email protected]

blog: blog.csdn.net/fulinus








線程的條件變量實例