多线程同步之条件变量

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

涉及到的函数有:

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("\n");
    return 0;
}

 REFERENCE:

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

posted @ 2015-08-15 16:05  Sawyer Ford  阅读(383)  评论(0编辑  收藏  举报