多线程练习题

注意要点:

进入pthread_cond_wait之前必须加互斥锁,以防止多线程同时请求pthread_cond_wait。

在进入pthread_cond_wait后等待时,该函数会将互斥锁解锁。

在离开pthread_cond_wait前,又会从新加锁。

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

#define THREAD_NUM 3

static unsigned int g_num = 0;
static pthread_t g_tarr[THREAD_NUM];
static pthread_cond_t g_cond;
static pthread_mutex_t g_mutex;

void* thn_t (void *arg) {
        int num = (int)arg;
        char var = 'a'+num;
        int i;
        printf ("var = %c\n", var);
        for ( ; ; ) {
                pthread_mutex_lock (&g_mutex);
                if (g_num % THREAD_NUM != num) {
                        pthread_cond_wait (&g_cond, &g_mutex);
                }
                printf ("%c\n", var);
                g_num++;
                pthread_mutex_unlock (&g_mutex);
                pthread_cond_broadcast (&g_cond);
                sleep (1);
        }
}

int main (void) {
        int i;
        void *ret;
        pthread_mutex_init (&g_mutex,0);
        pthread_cond_init (&g_cond,0);
        for (i = 0; i < THREAD_NUM; ++i) {
                pthread_create (&g_tarr[i],0,thn_t,(void*)i);
        }

        pthread_join (g_tarr[THREAD_NUM-1],&ret);
        return 0;
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值