zoukankan      html  css  js  c++  java
  • 多线程同步之条件变量

        条件变量是线程同步的另一种手段,主要逻辑就是等待和唤醒。条件不满足时,线程等待;条件满足,线程被(其他线程)唤醒。条件变量一般和互斥量一起使用,因为需要保证多线程互斥地修改条件。

    涉及到的函数有:

    int pthread_cond_init(pthread_cond_t *restrict cond,
    const pthread_condattr_t *restrict attr);
    
    int pthread_cond_destroy(pthread_cond_t *cond);
    
    int pthread_cond_wait(pthread_cond_t *restrict cond,
    pthread_mutex_t *restrict mutex); 
    
    int pthread_cond_signal(pthread_cond_t *cond); 
    
    int pthread_cond_broadcast(pthread_cond_t *cond);

    实战训练:

    有三个线程分别打印A、B、C,请用多线程编程实现,在屏幕上循环打印10次ABCABC…

    solution:

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    #define N 10
    #define M 3          //number of threads
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond;
    int m = 0;
    
    void* thr_fn(void *arg)
    {
        int index = (int)arg;
        char ch = 'A' + index;
        int i;
        for (i = 0; i < N; ++i)
        {
             pthread_mutex_lock(&mutex);
             while (index != m)
                 pthread_cond_wait(&cond, &mutex);
    
             printf("%c", ch);
             m = (m+1) % M;
             pthread_mutex_unlock(&mutex);
    
             pthread_cond_broadcast(&cond);
        }
        return (void*)0;
    }
    
    int main()
    {
        pthread_cond_init(&cond, NULL);
        pthread_t tid[M];
        int i;
        for (i = 0; i < M; ++i)
            pthread_create(&tid[i], NULL, thr_fn, (void*)i);
        for (i = 0; i < M; ++i)
            pthread_join(tid[i], NULL);
        pthread_cond_destroy(&cond);
        printf("
    ");
        return 0;
    }

     REFERENCE:

    【机试】华为2014校招机试:多线程循环打印十次ABC

  • 相关阅读:
    p1217晚餐(简单的dijkstra)
    [USACO07NOV]牛继电器Cow Relays
    [USACO15JAN]草鉴定Grass Cownoisseur
    [SDOI2009]Elaxia的路线
    图论dp [ZJOI2006]物流运输
    数位dp暂退-[ZJOI2010]数字计数
    数位dp进阶:[CQOI2016]手机号码
    数位dp入门-windy数
    借教室
    天天爱跑♂步
  • 原文地址:https://www.cnblogs.com/gattaca/p/4732623.html
Copyright © 2011-2022 走看看